簡體   English   中英

如何總結對象數組中相同字段的值?

[英]How to sum up values of same field in array of objects?

我有一個對象數組

const data = [
  { category: 'shopping', amount: 50 }, 
  { category: 'rent', amount: 1000 }, 
  { category: 'groceries', amount: 20 }, 
  { category: 'shopping', amount: 50 }
]

我正在嘗試總結每個類別的金額

const result = [
  { category: 'shopping', amount: 100 },
  { category: 'rent', amount: 1000 },
  { category: 'groceries', amount: 20 }
]

到目前為止,我正在考慮刪除類別的“重復項”並將它們存儲到一個數組中

const temp = data.map((obj) => {
  return obj.category
})

const categories = [...new Set(temp)] // ['shopping','rent','groceries']

有了以上內容,我正在考慮做一個嵌套循環,但經過多次嘗試,我失敗了。

任何幫助表示贊賞

您可以使用reduce()來做到這一點。

迭代給定數據,如果存在與當前項目具有相同category的項目,則添加amount ,否則將當前項目添加為新條目。

 const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; let result = data.reduce((acc, curr) => { let item = acc.find(item => item.category === curr.category); if (item) { item.amount += curr.amount; } else { acc.push(curr); } return acc; }, []); console.log(result);

這是使用 object 作為累加器的替代方法。 這具有性能優勢,因為我們不必在每次迭代時調用find() 感謝frodo2975的建議。

 const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; let result = Object.values(data.reduce((acc, curr) => { let item = acc[curr.category]; if (item) { item.amount += curr.amount; } else { acc[curr.category] = curr; } return acc; }, {})); console.log(result);

我將專注於有效計算每個類別的總數,然后以您需要的格式重組數據。 所以是這樣的:

// Construct an object mapping category to total amount.
const totals = data.reduce((totals, { category, amount }) => {
    totals[category] = (totals[category] || 0) + amount;
}, {});

// Format the data as you like.
const result = Object.entries(totals).map(([category, amount]) => ({ category, amount });

只是使用reduce方法的另一個版本:)

 const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; const result = data.reduce((a,c) => { a[c.category] = a[c.category] || {category: c.category, amount: 0}; a[c.category].amount += c.amount; return a; }, {}) console.log(Object.values(result));

暫無
暫無

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

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