Understanding the readability of JavaScript arrays.ORDeciphering

Recently, I've been working with a JSON OBJECT that looks something like this

{
  "kay1": "value1",
  "key2": "value2",
  "key3":{
    "key31": "value31",
    "key32": "value32",
    "key33": "value33"
  }
}

However, I am interested in converting it into a JSON ARRAY as shown below

[
  "value1",
  "value2",
  [
    "value31",
    "value32",
    "value33"
  ]
]

The reason behind my decision to switch from JSON OBJECT to JSON ARRAY is that it reduces network traffic and makes retrieving values more efficient.

One challenge I have encountered is that the readability of the ARRAY format is not as clear as the OBJECT format.

Does anyone have suggestions on how to enhance the readability of the JSON ARRAY?

Answer №1

After spending some time working on a solution, I have created a function that will transform every object in your data into an array. This revised code snippet below provides the desired outcome you've been looking for.


var objData = {
  "id1":"name1",
  "id2":"name2",
  "id3":{
    "subID1":"value1",
    "subID2":"value2",
    "subID3": {
      "nestedA" : "dataA",
      "nestedB" : "dataB"
    }
  }
};

ObjectConverter = {
  isObject : function(input) {
    if(Object.prototype.toString.call(input) === '[object Object]') {
        return true;
    }
    return false;
  },
  toArrayConversion : function(dataObj) {
     var objKeys = Object.keys(dataObj);
     var resultArr = [];
     objKeys.forEach(function(keyVal) {
        var newObjPush;
        if(ObjectConverter.isObject(dataObj[keyVal])) {
           newObjPush = ObjectConverter.toArrayConversion(dataObj[keyVal]);
        } else {
           newObjPush = dataObj[keyVal];
        }
        resultArr.push(newObjPush);
     });
     return resultArr;
  }
};

var finalOutcome = ObjectConverter.toArrayConversion(objData);

console.log(finalOutcome);

Answer №2

In my humble opinion, the ideal format is:

{
  "name":"John",
  "age":25,
  "interests":["reading", "hiking", "cooking"]
}

Answer №3

To ensure optimal performance, it is crucial to utilize the init method efficiently. Consider implementing a strategy where you either set up a scheme or assign static JSON to Storage.keys, and allocate your bulk data array to store.data. Following this setup, you can easily retrieve specific values using store.get("key3.key31"). Refer to this JSFiddle link for further clarification.

if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}


var data = {
  "kay1":"value1",
  "key2":"value2",
  "key3":{
    "key31":"value31",
    "key32":"value32",
    "key33":"value33"
  }
}


var Storage = function(data){
    this.rawData = data;
    return this;
}

Storage.prototype.init = function(){
    var self = this;
    var index = 0;
    var mp = function(dat, rootKey){

        var res = Object.keys(dat).map(function(key, i) {
            var v = dat[key];
            if (typeof(v) === 'object'){
                mp(v, key);
            } else {
                self.data.push(v);
                var nspace = rootKey.split(".").concat([key]).join(".");
                self.keys[nspace] = index++;
            }
        });
    }
    mp(this.rawData, "");
}

Storage.prototype.get = function(key){
    return this.data[this.keys[key]];
};

Storage.prototype.data = [];
Storage.prototype.keys = {};

var store = new Storage(data);
console.log(data);
store.init();
console.log("keys", store.keys);
console.log("data", store.data);

console.log("kay1=", store.get(".kay1"));
console.log("key2=", store.get(".key2"));
console.log("key3.key31=", store.get("key3.key31"));
console.log("key3.key32=",store.get("key3.key32"));
console.log("key3.key33=", store.get("key3.key33"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to present both Javascript and templates from parallel directories using express?

QUERY: Is there a way to modify the server.js file so that the three.js script in index.html does not display an error message like Cannot GET /node_modules/three/three.js? Code Snippet: index.html <!DOCTYPE html> <html lang="en"> <head&g ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

The system does not acknowledge NPM as a valid internal or external command

Here is the content of my package.json file for the server directory, which I am attempting to launch: { "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon src/app.js --exec 'npm ...

Is it a graphics card malfunction or a coding complication? Delving into THREE.JS WebGL

Recently, I created a cool scene using three.js that was running perfectly until today. Strangely, without any changes to the code, I started encountering an error in every major browser - Chrome, Firefox, and Edge. The error message I am seeing is: THREE. ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

Showing all columns in a table using Flutter

I'm currently developing a test application using Dart, which is designed to display and insert data into a database hosted on 000webhost.com. In my app, I'm trying to display JSON data in a table where all the columns are contained within a sin ...

activate a single on.click event to trigger additional actions - utilizing javascript and jQuery

My website features dynamically generated buttons that lead to specific pages. The challenge I'm facing is retrieving the automatically generated data-num value for each button and using it as a jQuery selector to redirect users to the corresponding p ...

The Helper Text fails to display the error, and the error message does not appear when the login data is incorrect

Currently, I am facing an issue with displaying error messages within my helper text component while using Material UI. Despite successfully testing my backend code using Postman to identify errors, I am unable to see the error message under the button whe ...

What is the procedure for extracting data from a JSON encoded string in PHP?

I've been trying to get a value from JSON encode, but I can't seem to figure out what I'm doing wrong. Can someone please help me? I'm still new at this so please be patient :) Here's my PHP code: <?php $data = json_decode("do ...

Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

Having trouble converting JSON to an object with Newtonsoft.Json library

I have encountered an issue with deserializing a sample JSON received from a service using C#. { "columns": [ "empid", "employeename", "currentAllocation", "Dept head", ...

empty responseText from GET request using AJAX

I've been working on a chatbox using AJAX and I've encountered an issue where my xhttp.responseText is coming back empty. In firebug, I can see that the GET request is being sent and the correct text is being returned, but for some reason it&apos ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

Is Node.js going to continue to provide support for its previous versions of node modules?

I currently have a website that relies on the following dependencies. While everything is working smoothly at the moment, I can't help but wonder about the future support of these packages by node.js. I've looked into the legacy documentation of ...

How to incorporate both images and text in a UIPickerView using Swift?

Can anyone provide an example showcasing how to integrate a UIPickerView in swift, including the display of both images and text using JSON for data loading? ...

JavaScript tag filtering system: Display only the div elements that contain all the specified classes in an array; otherwise, hide them

Can you provide some guidance on accomplishing this task? I am looking to toggle the visibility of a div based on its classes and an array. If the array contains the term something, then only divs with the class something will be displayed. If the array ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Exploring the contents of a JSON object

Just getting started with jquery and I'm attempting to parse a JSON object. This is my Jquery ajax call $(document).ready(function () { var resource = "v1/projects"; var url = '@Url.Action("Proxy")?resource=' + resource; ...

Nuxt middleware failing to verify user's logged-in status

I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve ...

Creating an interactive bootstrap modal: a step-by-step guide

For instance, I have 3 different tags with unique target-data for each one. <a class="btn btn-outline-primary btn-sm" href="#" data-toggle="modal" data-target="#firstdata"> DATA 1 </a> <a class=&q ...