Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

Group and sum nested objects by multiple keys with loadash

$
0
0

In the array below, I want to group by item and reason then calculate the total quantity:

item_movements = [
{
item: "Apple",
reason: 1,
quantity: 5
},
item: "Banana",
reason: 2,
quantity: 10
},
{
item: "Apple",
reason: 1,
quantity: 5
},
item: "Banana",
reason: 1,
quantity: 8
},
{
item: "Apple",
reason: 2,
quantity: 3
},
item: "Banana",
reason: 1,
quantity: 8
}
]

The result am trying to achieve is this:

item_totals = [
{
item: "Apple",
1: 10,
2: 3
},
{
item: "Banana",
1: 16,
2: 10
}

I was able to group by item using loadash like so:

  itemMovementbyItem() {
          var result = _(this.item_movements)
            .groupBy(x => x.item)
            .map((value, key) => ({
              item: key,
              item_movements: value
            }))
            .value()

          return result
        },

But I am having problems to group a second time by reason.

Any suggestion?


Viewing all articles
Browse latest Browse all 138134

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>