I have an object as:
[
{
"DATA": "2016-01-22",
"TOTAL": "7"
},
{
"DATA": "2016-01-25",
"TOTAL": "3"
},
{
"DATA": "2016-01-26",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "2"
},
{
"DATA": "2016-01-22",
"TOTAL": "1"
},
{
"DATA": "2016-01-25",
"TOTAL": "1"
},
{
"DATA": "2016-01-27",
"TOTAL": "1"
},
...
]
How can I shrink it down to something like below, this is, concatenate/join the TOTAL keys where the date is the same and fill with 0 in case the date doesn't repeat?:
[
{
"DATA": "2016-01-22",
"TOTAL": ["7", "1"]
},
{
"DATA": "2016-01-25",
"TOTAL": ["3", "1"]
},
{
"DATA": "2016-01-26",
"TOTAL": ["1", "0"]
},
{
"DATA": "2016-01-27",
"TOTAL": ["2", "1"]
}
]
I've been trying with this block of code, but can't get TOTAL keys all the same dimension - filled with zeros would be fine.
var output = [];
d.forEach(function(value) {
var existing = output.filter(function(v, i) {
return v.DATA == value.DATA;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].TOTAL = output[existingIndex].TOTAL.concat(value.TOTAL);
} else {
if (typeof value.TOTAL == 'string')
value.TOTAL = [value.TOTAL];
output.push(value);
}
});
console.log(JSON.stringify(output, null, 4));