我想减少这样的对象数组:
var data = [{
item: "Item 1",
pages: 30,
chapters: 3
},
{
item: "Item 1",
pages: 50,
chapters: 3
},
{
item: "Item 2",
pages: 10,
chapters: 3
}
]
但是聚合两个“字段”,所以在这种情况下它应该像这样结束:
[
{item: "Item 1", pages: 80, chapters: 6},
{item: "Item 2", pages: 10, chapters: 3}
]
我尝试过使用reduce,但无法聚合多个字段:
data.reduce((acc,cur) => {
acc[cur.item][pages] = acc[cur.item][pages] + cur.item.pages || cur.item.pages
acc[cur.item][chapters] = acc[cur.item][chapters] + cur.item.chapters || cur.item.chapters
return acc
},{})
但这会引发错误,因为它在累加器中找不到
pages
项。
是否可以减少聚合多个字段的数据?
var data = [{
item: "Item 1",
pages: 30,
chapters: 3
},
{
item: "Item 1",
pages: 50,
chapters: 3
},
{
item: "Item 2",
pages: 10,
chapters: 3
}];
const processedData = data.reduce((items, { item, pages, chapters }) => {
const ensureItemData = () =>
items.find(itemData => itemData.item === item)
?? (() => {
const itemData = { item, pages: 0, chapters: 0 };
items.push(itemData);
return itemData;
})();
const itemData = ensureItemData();
itemData.pages += pages;
itemData.chapters += chapters;
return items;
}, []);