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

JavaScript按id匹配合并对象数组属性 重命名重复键实现方案

两个对象数组按规则合并实现方案

需求说明

给定两个对象数组states和stateTypes,按照如下规则合并生成新数组:

  • 遍历states数组每一项,根据当前项的typeId去stateTypes数组中匹配id相等的项
  • 将匹配到的stateTypes项的属性合并到对应的states对象中:
    • 两者属性名无重复时,stateTypes的属性直接保留
    • 两者属性名重复时,给stateTypes的对应属性添加stageType-前缀后再合并

示例输入数据

{
  "states": [
    {
      "id": 1,
      "typeId": 1,
      "name": "CREATED",
      "description": "Created",
      "label": "Created",
      "perviousNotMatchKey": "Text"
    },
    {
      "id": 2,
      "typeId": 3,
      "name": "ASSIGNED",
      "description": "Assigned",
      "label": "Assigned",
      "perviousNotMatchKey": "Text"
    },
    {
      "id": 3,
      "typeId": 3,
      "name": "COMPLETED",
      "description": "Completed",
      "label": "Completed",
      "perviousNotMatchKey": "Text"
    }
  ],
  "stateTypes": [
    {
      "id": 1,
      "name": "PENDING",
      "description": "Pending",
      "label": "Pending",
      "newIncomingKey": "Text"
    },
    {
      "id": 2,
      "name": "IN_PROGRESS",
      "description": "In Progress",
      "label": "In Progress",
      "newIncomingKey": "Text"
    },
    {
      "id": 3,
      "name": "COMPLETED",
      "description": "Completed",
      "label": "Completed",
      "newIncomingKey": "Text"
    }
  ]
}

JavaScript实现代码

function mergeStateArrays(states, stateTypes) {
  // 转换为Map结构提升查询效率
  const stateTypeMap = new Map(stateTypes.map(type => [type.id, type]));

  return states.map(stateItem => {
    // 浅拷贝原对象,避免修改原始数据
    const resultItem = { ...stateItem };
    const matchedType = stateTypeMap.get(stateItem.typeId);
    
    // 无匹配项直接返回原对象
    if (!matchedType) return resultItem;

    // 遍历匹配到的类型对象属性,按规则合并
    Object.entries(matchedType).forEach(([key, value]) => {
      if (key in resultItem) {
        // 重名属性加前缀
        resultItem[`stageType-${key}`] = value;
      } else {
        // 非重名属性直接赋值
        resultItem[key] = value;
      }
    });

    return resultItem;
  });
}

代码说明

  • 提前将stateTypes转换为id为键的Map,数据量较大时可大幅提升匹配查询效率
  • 所有操作均基于浅拷贝生成的新对象,不会修改原始输入的两个数组内容
  • 兼容所有属性场景,无论新增属性、重名属性都可以按照规则正确处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:09:03