我有如下数组:
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是相同的,那么我忽略了关于如何只对其进行求和的链接。
发布于 2020-07-26 11:51:40
您需要在映射中进行减缩,否则名称会丢失,而累加器试图连接字符串,而不是总计一个数字。
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)
发布于 2020-07-26 11:52:40
使用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));
发布于 2020-07-26 11:52:38
这是你想要的:
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) }
}));
https://stackoverflow.com/questions/63099699
复制相似问题