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

如何在对象数组中合并同人员同公司的client字段为数组

合并数组中重复条目对应的Client字段

需求说明

当对象数组中姓名(name)与公司(company)均相同时,将对应条目的client字段值合并到同一个数组中;无重复的条目保留原client值格式。

输入数据

const employee = [
    {
        name: 'John',
        company: 'abc',
        client: 'BMW'
    },
    {
        name: 'Jack',
        company: 'abc',
        client: 'Volvo'
    },
    {
        name: 'John',
        company: 'abc',
        client: 'Mercedes'
    }
]

预期输出

[
    {
        name: 'John',
        company: 'abc',
        client: ['BMW', 'Mercedes']
    },
    {
        name: 'Jack',
        company: 'abc',
        client: 'Volvo'
    }
]

解决方案代码

const mergedEmployees = Object.values(employee.reduce((acc, curr) => {
    // 用name+company拼接唯一标识键
    const key = `${curr.name}-${curr.company}`;
    
    if (!acc[key]) {
        // 首次出现的条目,直接存入临时对象
        acc[key] = {...curr};
    } else {
        // 重复条目,合并client字段
        if (typeof acc[key].client === 'string') {
            acc[key].client = [acc[key].client];
        }
        acc[key].client.push(curr.client);
    }
    
    return acc;
}, {}));

console.log(mergedEmployees);

思路解释

  1. 分组标识:将name和company拼接成唯一键,确保只有两者完全匹配的条目才会被归为同一组。
  2. 遍历聚合:通过reduce遍历数组,用临时对象acc存储分组结果:
    • 首次遇到的条目直接复制存入acc;
    • 遇到重复分组时,先判断原有client是否为字符串,若是则转为数组,再将新的client值推入数组。
  3. 结果转换:用Object.values()将临时对象的取值转换为最终的数组格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:33:25