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

如何用原生JS实现多层JSON数组去重并合并重复项的items属性

原生JS实现同location条目合并

实现思路

核心是用键值对结构做临时聚合,避免嵌套遍历的性能损耗:

  • 用Map作为临时聚合容器,以location字段值为唯一键
  • 遍历原始数组每一项,不存在对应键就初始化存入,存在就把当前项的items追加到已有条目的items数组中
  • 遍历完成后取出Map中所有值,就是最终合并后的数组

完整实现代码

const originalArr = [
    {"location": "north", "items" : ["IT1", "IT2"]},
    {"location": "south", "items" : ["IT1", "IT2"]},
    {"location": "north", "items" : ["IT3", "IT4"]}
];

const locationAgg = new Map();

for (const entry of originalArr) {
    const { location, items } = entry;
    if (!locationAgg.has(location)) {
        // 初始化时做浅拷贝,避免修改原始数组的引用
        locationAgg.set(location, {
            location,
            items: [...items]
        });
        continue;
    }
    // 追加合并items
    const existed = locationAgg.get(location);
    existed.items.push(...items);
}

// 得到最终结果
const mergedArr = Array.from(locationAgg.values());

可选扩展

如果业务场景里相同location条目下的items可能存在重复值,需要自动去重的话,把合并逻辑替换成下面的写法即可:

// 替换原来的push逻辑,合并后自动去重
const existed = locationAgg.get(location);
existed.items = Array.from(new Set([...existed.items, ...items]));

运行上述代码得到的mergedArr结构和预期目标完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:54:17