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

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

"Improvements required for the search and filter functionality in the JSON

My JSON function retrieves image data and displays it in panels. Here is an example of the code: $.getJSON('iproducts.json',function(products){ var output = ""; $.each(products.appleitems, function(i, product) { output += "<di ...

Retrieve the first two elements from an array and iterate through each of them using a foreach

Currently, I have JSON data formatted like this: https://i.stack.imgur.com/PqOQ0.png I am attempting to create URLs using a foreach loop for an API that requires start and finish dates as parameters. For example, here is a sample URL -> My question is, ...

The command 'run-s' is not valid and cannot be found as an internal or external command. Please make sure it is a recognized program or batch file

Unexpectedly, I encountered an issue while attempting to utilize the npm link command to test my local package. Any ideas on how to resolve this? Operating System: Windows 10 Node version: 15.9.0 NPM version: 8.12.2 ...

Most effective method to avoid updating a node_modules package

tag: After downloading and installing a node_module (npm package)... I have customized the internal files within the node_modules folder to better fit my requirements. Although using it as a node_module is most convenient for me, I am concerned that futur ...

What is the best way to extract the data from a Json array and store it in an ArrayList?

Let me start by mentioning that I am a novice, so any assistance would be greatly appreciated. I have developed a car class within a form application. Each car instance has three properties: spaceNum, make, and model. All cars are stored in an ArrayList. ...

A guide to implementing polymorphic serialization without the use of annotations or mixins

In the city of Jackson, we have the option to utilize certain annotations: @JsonTypeInfo @JsonSubTypes @JsonSubTypes.Type These can be used for polymorphic serialization. We have two choices: Applying these annotations directly on the data model, which ...

Encountered an issue while attempting to access the JSON file. Error message: [json.decoder.JSONDecodeError: Anticipating property

Recently, I have been facing some difficulties while attempting to open a json file in Python 3.8 using the json library. My attempts so far have not been successful. Here is a minimal working example (MWE) of my code: with open(pbit_path + file_name, &ap ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

Retrieve a list of applications in JSON format from your Heroku account

Building a Node/Express app to showcase my portfolio. I found an interesting CLI command that allows me to view a JSON list of my apps and their properties directly in the terminal: https://devcenter.heroku.com/articles/using-the-cli#app-commands Now, I& ...

When attempting to implement sound on hover with an <a attribute containing an image>, the functionality is not functioning as expected

Is there a way to make a sound play only once when hovering over a list item that contains an image? Here is the HTML and JavaScript code I am using: function playclip() { var audio = document.getElementsByTagName("audio")[0]; audio.play(); } <ul ...

The Lightgallery plugin is creating three duplicates of the slides

I am currently facing an issue with a gallery that loads images from an API and displays them using the lightgallery plugin. Upon implementing the lightbox in the correct location (view question here), I discovered that the plugin is generating three slid ...

What is the best way to initiate the handling of newly inserted values in a Vuex store?

I am working with a Vuex store that stores entries: const store = createStore({ state() { return { entries: [ { id: 1, date-of-birth: "2020-10-15T14:48:00.000Z", name: "Tom", }, ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

The link button appears unselected without a border displayed

I am facing an issue with a link button in my code. Here is the snippet: <div class="col-2"> <a type="button" routerLink="auto-generate-schedules/generate" class="btn btn-primary mb-2">Generate Sche ...

Tips for submitting a form textarea input from CKEditor using AJAX

I am currently utilizing CKEditor, jQuery, and the jQuery form plugin. My objective is to submit the content of the CKEditor form through an Ajax query. Below is the code I have implemented: <form id="article-form" name="article-form" method="post" act ...

React's router activeClassName feature fails to apply the active class to child routes

<ul className="right hide-on-med-and-down"> <li><IndexLink to="/" activeClassName="active">ABOUT</IndexLink></li> <li><Link to="blog" activeClassName="active">BLOG</Link></li> <li><Link t ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...