2016-04-28 19 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