用JavaScript计算分组数组中的金额



我正试图用他们的总金额生成一个新的人员数组。我能够过滤掉基于个人的金额。有人能帮忙吗?

mockData = [{
name: 'John',
title: 'Gas',
amount: 20.10
}, {
name: 'John',
title: 'Taco bell',
amount: 4.10
}, {
name: 'Doe',
title: 'Food',
amount: 30.50
}, {
name: 'Doe',
title: 'Groceries',
amount: 10.20
}, {
name: 'Doe',
title: 'Paint',
amount: 5
}];
const distinctItems = [...new Map(mockData.map(item => [item.name, item])).values()].map(({
name
}) => name);
const filterTotals = (expenses, person) =>
expenses.filter(({
name
}) => name === person)
const result = distinctItems.map((name) => filterTotals(mockData, name));
console.log(result)

我期待的最终结果是

[{name: 'John', total: 24.20}, {name: 'Doe', total: 45.7}]

您可以对数据进行单个循环,并将amount添加到同一个name

const
data = [{ name: 'John', title: 'Gas', amount: 20.10 }, { name: 'John', title: 'Taco bell', amount: 4.10 }, { name: 'Doe', title: 'Food', amount: 30.50 }, { name: 'Doe', title: 'Groceries', amount: 10.20 }, { name: 'Doe', title: 'Paint', amount: 5 }],
result = Array.from(
data.reduce((m, { name, amount }) => m.set(name, (m.get(name) || 0) + amount), new Map),
([name, total]) => ({ name, total })
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

将数组缩减为以键为名称的对象&值作为该名称的总额&然后您可以使用Object.entries来迭代键&值

const mockData = [{
name: 'John',
title: 'Gas',
amount: 20.10
}, {
name: 'John',
title: 'Taco bell',
amount: 4.10
}, {
name: 'Doe',
title: 'Food',
amount: 30.50
}, {
name: 'Doe',
title: 'Groceries',
amount: 10.20
}, {
name: 'Doe',
title: 'Paint',
amount: 5
}];
const obj = mockData.reduce((map, obj) => {
const {
name,
amount
} = obj
map[name] = name in map ? map[name] + amount : amount
return map
}, {})
const result = Object.entries(obj).map(([key, value]) => ({
name: key,
total: value.toFixed(2)
}))
console.log('result', result)

mockData = [{
name: 'John',
title: 'Gas',
amount: 20.10
}, {
name: 'John',
title: 'Taco bell',
amount: 4.10
}, {
name: 'Doe',
title: 'Food',
amount: 30.50
}, {
name: 'Doe',
title: 'Groceries',
amount: 10.20
}, {
name: 'Doe',
title: 'Paint',
amount: 5
}];
const totalAmountMap = mockData.reduce((accumulator, { name, amount }) => {
accumulator[name] = (accumulator[name] || 0) + amount;
return accumulator;
}, {});
const totalAmountArray = Object.keys(totalAmountMap).map((name) => ({
name,
total: totalAmountMap[name]
}));
console.log(totalAmountArray);

最新更新