将值添加到JSON数组对象

时间:2013-07-15 08:53:38

标签: jquery json

我有一个看起来像这样的数组

[{
    "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"
}

1 个答案:

答案 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);

工作示例: http://jsfiddle.net/vJjSX/