[Solved] convert json data to another format using javascript [closed]


This proposal features Array#forEach with an object for the month group.

The object is created without any prototypes or properties, it is really an empty. This could be necessary if a hash has a value of a property of a not empty object.

var array = [{ month: 'Jan', cat: 'A', val: 20 }, { month: 'Jan', cat: 'B', val: 5 }, { month: 'Jan', cat: 'C', val: 10 }, { month: 'Feb', cat: 'A', val: 30 }, { month: 'Feb', cat: 'B', val: 10 }, { month: 'Feb', cat: 'C', val: 20 }],
    grouped = [];

array.forEach(function (a) {
    if (!this[a.month]) {
        this[a.month] = { month: a.month };
        grouped.push(this[a.month]);
    }
    this[a.month][a.cat] = (this[a.month][a.cat] || 0) + a.val;
}, Object.create(null));

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

2

solved convert json data to another format using javascript [closed]