I need to convert a flat array where the similar data is held in separate properties into an array of arrays grouping the data fields from each property together. Hopefully an example will make sense of this.
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 },
...
]
Output required:
[{"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 that I can do this by 'manually' setting up 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);
and then iterating through the original array grabbing 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 there are in fact a dozen of these data properties and this method seems long-winded. Is there a way I can populate the new array by looping through the data properties?