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

对象结构一致的两个数组对比与合并处理需求

对比包含对象的两个数组并更新状态

问题场景

需要对比两个结构不同的数组:初始数组的元素包含嵌套item对象和active状态,新数组仅包含item结构的对象。需按规则完成数组更新:

初始数组

[
    {
        "item": {
            "id": '1',
            "path": "some text"
        },
        "active": true
    },
    {
        "item": {
            "id": '2',
            "path": "some text"
        },
        "active": true
    },
    {
        "item": {
            "id": '4',
            "path": "some text"
        },
        "active": false
    },
    {
        "item": {
            "id": '10',
            "path": "some text"
        },
        "active": false
    }
]

新数组

[
    {
        "id": '1',
        "path": "some text"
    },
    {
        "id": '4',
        "path": "some text"
    },
    {
        "id": '6',
        "path": "some text"
    }
]

需求

  • 保留ID为1、4的项,维持原有active状态;
  • 删除初始数组中ID不在新数组内的项(如ID为2、10的元素);
  • 添加新数组中新增的ID为6的项,默认设置active为false。

解决方案

通过构建映射表快速匹配状态,再遍历新数组生成结果:

const initialArray = [
    {
        "item": {
            "id": '1',
            "path": "some text"
        },
        "active": true
    },
    {
        "item": {
            "id": '2',
            "path": "some text"
        },
        "active": true
    },
    {
        "item": {
            "id": '4',
            "path": "some text"
        },
        "active": false
    },
    {
        "item": {
            "id": '10',
            "path": "some text"
        },
        "active": false
    }
];

const newArray = [
    {
        "id": '1',
        "path": "some text"
    },
    {
        "id": '4',
        "path": "some text"
    },
    {
        "id": '6',
        "path": "some text"
    }
];

// 构建初始数组的ID与active状态映射
const activeMap = initialArray.reduce((acc, curr) => {
    acc[curr.item.id] = curr.active;
    return acc;
}, {});

// 生成最终结果数组
const result = newArray.map(item => ({
    item: item,
    active: activeMap[item.id] ?? false
}));

逻辑说明

  1. 构建映射表:用reduce将初始数组转换为以item.id为键、active值为值的对象,实现O(1)时间复杂度的状态查找;
  2. 生成结果:遍历新数组元素,通过映射表判断是否存在原有状态——存在则沿用,不存在则设为false,同时自动过滤初始数组中不在新数组内的元素。

预期结果

[
    {
        "item": {
            "id": '1',
            "path": "some text"
        },
        "active": true
    },
    {
        "item": {
            "id": '4',
            "path": "some text"
        },
        "active": false
    },
    {
        "item": {
            "id": '6',
            "path": "some text"
        },
        "active": false
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 22:43:21