-2

My base data is as following..

[{
    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
}]

I need to convert it into the following using javascript..

[{
    month: 'Jan',
    A: 20,
    B: 5,
    C: 10
}, {
    month: 'Feb',
    A: 30,
    B: 10,
    C: 20
}]

If the base data only had cat and val..

I could have tried something like..

data[e.cat] = e.val;

But grouping by month has got me.. Any help is sincerely appreciated..

Arnab
  • 2,324
  • 6
  • 36
  • 60
  • http://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes – mplungjan May 24 '16 at 14:58
  • What effort have you put into this? What are the specific issues you ran into? This question seems more like a "fix my issue for me". – Justus Romijn May 24 '16 at 15:00

1 Answers1

5

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392