-1

I have an API which returns a JSON object like this:

plans: [{
    0 : {plan: "gold", amount: 5000},
    1: {plan: "silver", amount: 2000},
    3: {plan: "silver", amount: 1000},
    4: {plan: "gold", amount: -4000}
}]

I want to group the result by plan. So here is the expected result:

groupedPlans: [{
    "gold" : {amount: 1000},
    "silver" : {amount: 3000}
}]

Is it possible to do such a thing using JS? I know in other languages like SQL you can do that simply by using GROUP BY plan. But not sure how can I do that in JS.

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • 1
    JS doesn't have a standard "group by" like in SQL. This may help https://stackoverflow.com/questions/67111048/javascript-how-to-groupby, and using reduce may be a good start – evolutionxbox Jan 23 '23 at 11:36
  • @ChrisG yes right – Martin AJ Jan 23 '23 at 11:37
  • 1
    Do you really have an array of single object with 0..4 as keys? – Jan Pfeifer Jan 23 '23 at 11:40
  • @JanPfeifer yeah here is the real output: https://i.stack.imgur.com/8d8jJ.png – Martin AJ Jan 23 '23 at 11:41
  • See [Converting JavaScript object with numeric keys into array](/q/20881213/4642212) and [Sum JavaScript object propertyA values with the same object propertyB in an array of objects](/q/19233283/4642212). Get familiar with [how to access and process objects, arrays, or JSON](/q/11922383/4642212), and use the static and instance methods of [`Object`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Jan 23 '23 at 11:48
  • @MartinAJ there's no object with 0..4 as keys in the screenshot. `plans` is an array – evolutionxbox Jan 23 '23 at 12:14

1 Answers1

1

You could get a flat array and group by plan.

const
    plans = [{ 0: { plan: "gold", amount: 5000 }, 1: { plan: "silver", amount: 2000 }, 3: { plan: "silver", amount: 1000 }, 4: { plan: "gold", amount: -4000 } }],
    result = plans
        .flatMap(Object.values)
        .reduce((r, { plan, amount }) => {
            (r[plan] ??= { amount: 0 }).amount += amount;
            return r;
        }, {});

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you, working as expected. Just the data I provided was a simplified of the real data, could you please tell me how can I add `user_id` to the result under `amount` too? https://jsfiddle.net/npgem0qt/ – Martin AJ Jan 23 '23 at 11:53
  • just destructure this property and add it to the default object, where `amount` is. – Nina Scholz Jan 23 '23 at 12:18