简体   繁体   中英

building an array object by pushing json

I have two objects as follows:

var id="one";
var arrobj = Array[2]
     0: Object
        name : "a"
        desc : "desc1"
     1: Object
        name : "b"
        desc : "desc2"

I am trying to build the object in the following format :

var secondobj = [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]

I tried this :

var secondobj= new Array();
var samplejson = {};

I just gave

samplejson.name = id;

After this I am a bit confused as in how to push values to get the above data structure.

这很简单:

samplejson[id]=arrobj;
var arrobj = [{
"name" : "a",
"desc" : "desc1"
},{
"name" : "b",
"desc" : "desc2"
}]
var secondobj = []; 
secondobj.push({
one : arrobj
})
console.log(secondobj);

Check this jsfiddle for demo

To make the above structure you can try this:

var secondobj= new Array();
var samplejson = {};
samplejson.one = arrobj;
secondobj.push(samplejson);
console.log(secondobj) // this will give [{ "one" : [{ name:"a",desc:"desc1"},{name:"b",desc :"desc2"}] }]

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