I am looking to transform a flat array containing similar data in separate properties into an array of arrays that groups the data fields from each property together. It might be easier to understand with an example.
The original array:
[{"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 },
...
]
Desired output:
[{"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}]},
]
I know I can achieve this by manually creating objects for each data field and adding them to the new array:
var mtm1 = { mtm: 1, values: [] }, mtm2 = { mtm: 2, values: [] }, mtm3 = { mtm: 3, values: [] };
var dataByPoint = [];
dataByPoint.push(mtm1);
dataByPoint.push(mtm2);
dataByPoint.push(mtm3);
Then by looping through the original array, I can retrieve the data for each object:
$.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);
});
However, since there are numerous data properties, this method seems cumbersome. Is there a more efficient way to populate the new array by iterating through the data properties?