我有一个数组如下:
const myArray = [
{
name: 'banana',
quotas: [
{
title: 'innerBanana1',
percent: 0.3
},
{
title: 'innerBanana2',
percent: 0.4
}
]
},
{
name: 'apple',
quotas: [
{
title: 'innerApple1',
percent: 0.6
},
{
title: 'innerApple2',
percent: 0.2
}
]
}
]
仅当配额数组属于同一外部对象(又名:名称相同)时,我才希望对它们进行总计。
预期结果
finalArray = [
{ name: 'banana', percent: 0.7 },
{ name: 'apple', percent: 0.8 }
]
我尝试过
const sum = quotaGroups
.map(quotaGroup => quotaGroup.quotas)
.reduce((accumulator, groupedQuota) => {
return accumulator + groupedQuota[0].percent
})
但是它显然不起作用。如果quotas
相同,我将缺少有关如何仅对内部对象的name
求和的链接
答案 0 :(得分:1)
您需要在映射内进行归约,否则名称会丢失,并且累加器试图连接字符串,而不是合计数字。
const myArray = [
{
name: 'banana',
quotas: [{title: 'innerBanana1', percent: 0.3}, {title: 'innerBanana2', percent: 0.4}]
},
{
name: 'apple',
quotas: [{title: 'innerApple1', percent: 0.6}, {title: 'innerApple2', percent: 0.2}]
}
]
const sum = myArray
.map(quotaGroup => ({
name: quotaGroup.name,
percent: quotaGroup.quotas.reduce((acc, item) => acc + item.percent, 0)
}))
console.log(sum)
答案 1 :(得分:1)
使用map
和reduce
const sum = (arr) =>
arr.map(({ quotas, name }) => ({
name,
percent: quotas.reduce((sum, { percent }) => sum + percent, 0),
}));
const myArray = [
{
name: "banana",
quotas: [
{
title: "innerBanana1",
percent: 0.3,
},
{
title: "innerBanana2",
percent: 0.4,
},
],
},
{
name: "apple",
quotas: [
{
title: "innerApple1",
percent: 0.6,
},
{
title: "innerApple2",
percent: 0.2,
},
],
},
];
console.log(sum(myArray));
答案 2 :(得分:0)
这就是您想要的:
const myArray = [
{
name: 'banana',
quotas: [
{
title: 'innerBanana1',
percent: 0.3
},
{
title: 'innerBanana2',
percent: 0.4
}
]
},
{
name: 'apple',
quotas: [
{
title: 'innerApple1',
percent: 0.6
},
{
title: 'innerApple2',
percent: 0.2
}
]
}
];
console.log(myArray.map(({ name, quotas }) => {
return { name, percent: quotas.reduce((a, { percent }) => a + percent, 0) }
}));
答案 3 :(得分:0)
如下使用map
和reduce
的组合
const finalArray = myArray.map(item => ({
name: item.name,
percent: item.quotas.reduce((acc, cur) => acc + cur.percent, 0)
}));
答案 4 :(得分:0)
let finalArray = myArray.map(item => {
let percent = 0;
item.quotas.forEach(function (obj) {
percent += obj.percent
});
return {
name: item.name,
percent: percent
}
})