简体   繁体   中英

Push multiple json array - javascript

I have 2 json object. i need to push inside array like this. Later i need to store the complete object in localstorage

function(cObj,bObj) { }

First array i should get.

object
        localArray: Array[2]
            cObj
                ....
            bObj

Again when the function is called, i should get

object
        localArray: Array[2]
            cObj
                ....
            bObj
        localArray: Array[2]
            cObj
                ....
            bObj    

This is what i am doing.

localObj = {}
localObj.localArray = [];   


localObj.localArray.push(cObj,bObj);
localStorage.localObj = JSON.stringify(localObj);

How to store the complete object in localstorage?

The keys in your object should be unique so if you want something like this

object
    localArray: Array[2]
        cObj
            ....
        bObj
    localArray: Array[2]
        cObj
            ....
        bObj   

The closest you're going to get to this, is with an object like that has an array of objects which encompass the key you would originally want to have repeated that can't be repeated because keys in an object should be unique:

cObj = {
  key: value
};

bObj = {
  key: value
};

// your local object would look like this 

{
  data: [
    {
      localArray: [
        cObj,
        bObj
      ]
    },
    {
      localArray: [
        cObj,
        bObj
      ]
    },
    ...
  ]
}

You could then just use the following code to update this object:

localObj.data.push({localArray: [cObj,bObj]});

And you would use it like this in your function:

localObj = {}
localObj.localArrays = [];

localObj.localArrays.push({
  localArray: [cObj, bObj]
});
localStorage.localObj = JSON.stringify(localObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM