簡體   English   中英

如何使用 Lodash 按多個鍵分組並將其值匯總到一組對象中?

[英]How to group by more than one key and sum its values in an array of objects, using Lodash?

在下面的數組中,我想按itemreason分組,然后計算總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
  }
];

我想要達到的結果是這樣的:

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

我能夠像這樣使用 Loadash 按item分組:

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

    return result
  }
})

但是我在按reason進行第二次分組時遇到了問題。

您可以在按'item'分組后直接對屬性求和。

 function itemMovementbyItem(array) { return _(array) .groupBy('item') .map(group => ({ item: group[0].item, 1: _.sumBy(group, o => o.reason === 1 ? o.quantity : 0), 2: _.sumBy(group, o => o.reason === 2 ? o.quantity : 0) })) .value(); } var 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 }]; console.log(itemMovementbyItem(item_movements));
 .as-console-wrapper { max-height: 100% !important; top: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

使用reduce以鍵為項目構建一個對象。 從對象中獲取Object.values

 const 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 } ]; const all = item_movements.reduce((acc, { item, reason, quantity }) => { acc[item] = item in acc ? { ...acc[item], [reason]: (acc[item][reason] || 0) + quantity } : { item, [reason]: quantity }; return acc; }, {}); const item_totals = Object.values(all); console.log(item_totals);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM