Xplora Xplora - 7 months ago 14
Javascript Question

How to merge JSON objects using JavaScript?

How to merge JSON objects using plain(without jQuery) JavaScript?

Requirement is to:

Convert from:

chartData=[
{"date":"2014-05-1","CAT1":0.1},
{"date":"2014-05-1","CAT2":0.2},
{"date":"2014-05-1","CAT3":0.3},
{"date":"2014-05-1","UNSET":0.4},
{"date":"2014-05-2","CAT1":0.4},
{"date":"2014-05-2","CAT2":0.3},
{"date":"2014-05-2","CAT3":0.2},
{"date":"2014-05-2","UNSET":0.1}
];


Convert To:

chartData=[
{"date":"2014-05-1","CAT1":0.1,"CAT2":0.2,"CAT3":0.3,"UNSET":0.4},
{"date":"2014-05-2","CAT1":0.4,"CAT2":0.3,"CAT3":0.2,"UNSET":0.1}
]

Answer

Here's an example of how to do this... no jquery required.

chartData=[{"date":"2014-05-1","CAT1":0.1},{"date":"2014-05-1","CAT2":0.2},{"date":"2014-05-1","CAT3":0.3},{"date":"2014-05-1","UNSET":0.4},{"date":"2014-05-2","CAT1":0.4},{"date":"2014-05-2","CAT2":0.3},{"date":"2014-05-2","CAT3":0.2},{"date":"2014-05-2","UNSET":0.1}];

function groupProps(orig, key) {
    var newArr = [],
        groups = {},
        newItem, i, j, cur;
    for (i = 0, j = orig.length; i < j; i++) {
        cur = orig[i];
        if (!(cur[key] in groups)) {
            groups[cur[key]] = {date: cur[key] };
            newArr.push(groups[cur[key]]);
        }        
        for (var prop in cur) {
            if (prop != key) {
                groups[cur[key]][prop] = cur[prop];
            }
        }
    }
    return newArr;
}

console.log(groupProps(chartData, "date"))