You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理对象数组:合并唯一title、求和count并统一size为0

解决方案

要实现按title去重、求和对应count且固定size为0的需求,可以通过分组统计的方式实现,具体步骤如下:

1. 分组统计每个title的总count

先遍历数组,用对象存储每个title对应的count总和:

const items = [
    {title: 'pepperoni', size: 0, count: 1},
    {title: 'pepperoni', size: 1, count: 3},
    {title: 'pepperoni', size: 2, count: 1},
    {title: 'cheese', size: 0, count: 2}
];

// 分组统计逻辑
const grouped = {};
items.forEach(item => {
    // 初始化未统计过的title的count为0
    if (!grouped[item.title]) {
        grouped[item.title] = 0;
    }
    // 累加当前item的count
    grouped[item.title] += item.count;
});

2. 转换为目标格式数组

将分组后的对象转换为size固定为0的数组:

const result = Object.entries(grouped).map(([title, count]) => ({
    title,
    size: 0,
    count
}));

console.log(result);
// 输出:
// [
//     {title: 'pepperoni', size: 0, count: 5},
//     {title: 'cheese', size: 0, count: 2}
// ]

适配你给出的期望结果(cheese count为0)

如果需要让仅存在size=0的title的count为0,可以在累加时增加判断:

const grouped = {};
items.forEach(item => {
    if (!grouped[item.title]) {
        grouped[item.title] = 0;
    }
    // 只累加size不等于0的count
    if (item.size !== 0) {
        grouped[item.title] += item.count;
    }
});

const result = Object.entries(grouped).map(([title, count]) => ({
    title,
    size: 0,
    count
}));

console.log(result);
// 输出:
// [
//     {title: 'pepperoni', size: 0, count: 4},
//     {title: 'cheese', size: 0, count: 0}
// ]

(注:这里pepperoni的count为4,和你给出的期望结果5有差异,推测你给出的期望结果可能是笔误,若需要所有count累加,用第一种方法即可)

为什么你的尝试没成功?

你使用filter仅筛选出了title=pepperoni且size=0的单个条目,没有实现分组求和的核心逻辑,因此无法得到目标结果。

内容的提问来源于stack exchange,提问作者vinograd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:54:18