我有一个看起来像这样的数组
[{
"Inventory": {
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
},
"Quality": {
"dashboard_id": "Quality",
"filter_by": "Location",
"yAxis": "SampleNo",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}
}]
我需要在每个对象中添加更多值。如何添加到现有阵列,使其看起来像这样
{
"Inventory": [{
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}, {
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}],
"Quality": {
"dashboard_id": "Quality",
"filter_by": "Location",
"yAxis": "SampleNo",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}
}
我使用nestedData[dashId] = data;
其中dashId由Quality
,'库存'等组成。
数据是
{
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}
答案 0 :(得分:4)
使用文字语法构建一个新的Object
,该语法包含所需的数组,并将源数组中的对象分配给对象中的相应属性。
var arr = [{
"Inventory": {
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
},
"Quality": {
"dashboard_id": "Quality",
"filter_by": "Location",
"yAxis": "SampleNo",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
}
}];
var obj = {Inventory:[arr[0].Inventory], Quality:[arr[0].Quality]};
obj.Inventory.push({
"dashboard_id": "Inventory",
"filter_by": "Location",
"yAxis": "Quantity",
"title": "",
"chart_type": "-------Select-------",
"mainchart": "Yes"
});
console.log(obj);