1

私はこのような配列を持っています

[{
    "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、「Inventory」などで構成されます。

データは

{
    "dashboard_id": "Inventory",
    "filter_by": "Location",
    "yAxis": "Quantity",
    "title": "",
    "chart_type": "-------Select-------",
    "mainchart": "Yes"
}
4

1 に答える 1

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/

于 2013-07-15T09:00:16.583 に答える