我需要將平面數組轉換爲數組,將相似數據保存在單獨的屬性中,並將數組中的數據字段組合在一起。希望一個例子能夠理解這一點。創建新的javascript陣列從對象屬性中提取數據
原始陣列:
[{"MtmDate":"2014-10-24", "MouldingID":"1233B", "ID":38, "Mtm01":5.10, "Mtm02":6.63,"Mtm03":5.84 },
{"MtmDate":"2014-10-25", "MouldingID":"1233B", "ID":39, "Mtm01":5.13, "Mtm02":6.21,"Mtm03":6.64 },
{"MtmDate":"2014-10-26", "MouldingID":"1233B", "ID":40, "Mtm01":5.68, "Mtm02":5.95,"Mtm03":6.37 },
...
]
輸出必需的:
[{"Mtm": 1, values: [{"MtmDate": "2014-10-24", "ID":38, data: 5.10},
{"MtmDate": "2014-10-25", "ID":39, data: 5.13},
{"MtmDate": "2014-10-26", "ID":40, data: 5.68}]},
{"Mtm": 2, values: [{"MtmDate": "2014-10-24", "ID":38, data: 6.63},
{"MtmDate": "2014-10-25", "ID":39, data: 6.21},
{"MtmDate": "2014-10-26", "ID":40, data: 5.95}]},
{"Mtm": 3, values: [{"MtmDate": "2014-10-24", "ID":38, data: 5.84},
{"MtmDate": "2014-10-25", "ID":39, data: 6.64},
{"MtmDate": "2014-10-26", "ID":40, data: 6.37}]},
]
我知道我可以通過爲每個數據字段「手動」設置對象,並把它們添加到新的數組執行此:
var mtm1 = { mtm: 1, values: [] }, mtm2 = { mtm: 2, values: [] }, mtm3 = { mtm: 3, values: [] };
var dataByPoint = [];
dataByPoint.push(mtm1);
dataByPoint.push(mtm2);
dataByPoint.push(mtm3);
然後迭代通過原始數組獲取每個對象的數據:
$.each(d, function(index, value) {
var details1 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm01 };
if (details1.data) dataByPoint[0].values.push(details1);
var details2 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm02 };
if (details2.data) dataByPoint[1].values.push(details2);
var details3 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm03 };
if (details3.data) dataByPoint[2].values.push(details3);
});
但實際上有一打這些數據屬性,這種方法看起來很囉嗦。有沒有辦法通過循環訪問數據屬性來填充新數組?
你已經明白了 - 這很好,謝謝 – 2015-02-23 16:56:52