通过推送json来构建数组对象

时间:2016-04-28 04:28:53

标签: javascript jquery arrays json

我有两个对象如下:

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

我正在尝试使用以下格式构建对象:

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

我试过了:

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

我刚刚给了

samplejson.name = id;

在此之后,我对如何推送值以获得上述数据结构感到困惑。

3 个答案:

答案 0 :(得分:2)

这很简单:

samplejson[id]=arrobj;

答案 1 :(得分:1)

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

选中此jsfiddle进行演示

答案 2 :(得分:1)

要制作上述结构,您可以尝试:

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"}] }]