2016-04-28 41 views
1

建立一个数组对象,我有两个目的如下:推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; 

在此之后,我有点困惑,因为在如何推动值来获得上述数据结构。

+2

'VAR secondobj =新阵列(); var samplejson = {}; samplejson.one = arrobj;' – Rayon

回答

2

这是一个简单的:

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

检查这个jsfiddle用于演示

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

samplejson.one = arrobj;由于“one”的值是动态的,因此变成硬编码值 – user1907849