mjpramos mjpramos - 1 month ago 8
Javascript Question

Flatten Javascript object array

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));

Answer
var someData = [] // <- your instantiated array in question.
var transformedData = [];

var highestCount = 0;

someData.forEach(x => {
    var foundIndex = transformedData.findIndex((ele) => ele.DATA === x.DATA);
    if (foundIndex < 0) {
        transformedData
            .push({DATA : x.DATA, TOTAL : [x.TOTAL]});
    } else {
        transformedData[foundIndex]
            .TOTAL.push(x.TOTAL);
        var currentCountAtIndex = transformedData[foundIndex].TOTAL.length;
        if (highestCount < transformedData[foundIndex].TOTAL.length) highestCount = currentCountAtIndex;
    }
});

// fill any indicies in array that are lower than the highest count with 0
transformedData
    .forEach(x => {
        if (x.TOTAL.length < highestCount) {
            while(x.TOTAL.length < highestCount) {
                x.TOTAL.push(0);
            }
        }
    });
Comments