我是 JS 的新手,我在將一個陣列中的值匯總到另一個陣列中時遇到了問題。
我有這個資料:
const data = [
{
category: 'personal',
amount: 80000,
month: 'Diciembre',
},
{
category: 'comida',
amount: 207000,
month: 'Diciembre',
},
{
category: 'comida',
amount: 43000,
month: 'Diciembre',
},
{
category: 'salidas',
amount: 124000,
month: 'Diciembre',
},
{
category: 'casa',
amount: 450505,
month: 'Diciembre',
},
{
category: 'casa',
amount: 500000,
month: 'Diciembre',
},
{
category: 'varios',
amount: 260000,
month: 'Diciembre',
},
{
category: 'casa',
amount: 296300,
month: 'Diciembre',
},
];
我想將其轉換為以下內容:
const dataSummarized = [
{
category: 'personal',
amount: TOTAL_AMOUNT_PERSONAL_CATEGORY
month: 'Diciembre',
},
{
category: 'comida',
amount: TOTAL_AMOUNT_COMIDA_CATEGORY
month: 'Diciembre',
},
{
category: 'salidas',
amount: TOTAL_AMOUNT_SALIDAS_CATEGORY,
month: 'Diciembre',
},
{
category: 'casa',
amount: TOTAL_AMOUNT_CASA_CATEGORY,
month: 'Diciembre',
}
];
我嘗試了幾種選擇,但沒有結果。
我嘗試過的一些解決方案在這里發布Sum javascript object propertyA values with same object propertyB in array of objects
顯然,我錯過了一些東西,因為我無法讓它作業:(
提前致謝!
uj5u.com熱心網友回復:
然后我們可以使用Array.reduce()按類別,然后按月對專案進行分組(我假設您想要每月的費用總額)。
我們根據類別和月份創建一個分組鍵,然后對每個鍵的總金額求和:
const data = [ { category: 'personal', amount: 80000, month: 'Diciembre', }, { category: 'comida', amount: 207000, month: 'Diciembre', }, { category: 'comida', amount: 43000, month: 'Diciembre', }, { category: 'salidas', amount: 124000, month: 'Diciembre', }, { category: 'casa', amount: 450505, month: 'Diciembre', }, { category: 'casa', amount: 500000, month: 'Diciembre', }, { category: 'varios', amount: 260000, month: 'Diciembre', }, { category: 'casa', amount: 296300, month: 'Diciembre', }, ];
const result = Object.values(data.reduce((acc, { category, month, amount }) => {
const key = `${category}-${month}`;
acc[key] = acc[key] || { category, month, amount: 0 };
acc[key].amount = amount;
return acc;
}, {}));
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375425.html
標籤:javascript 数组
