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

如何仅当dependentId为Null时,基于ID匹配为object1添加status属性

按条件为对象匹配并添加属性

需求:仅当object1中对象的dependentId为null时,根据employeeId与object2中newEmployeeId的匹配关系,将object2对应的status属性添加到object1的对应对象中。
预期结果:Ben、Jim和Dan的status分别为Complete、Updating和Finished;Lauren因dependentId不为null,不会拥有status属性。

原始数据

var object1 = [ 
    { name: 'Ben', employeeId: 1, dependentId: null },
    { name: 'Lauren', employeeId: 1, dependentId: 5},
    { name: 'Jim', employeeId: 2, dependentId: null },
    { name: 'Dan', employeeId: 3, dependentId: null}
];

var object2 = [ 
    { status: 'Complete', newEmployeeId: 1 },
    { status: 'Updating', newEmployeeId: 2 },
    { status: 'Finished', newEmployeeId: 3 }
];

实现方案

先把object2转换成以newEmployeeId为键的Map,快速匹配对应的status;之后遍历object1,只处理dependentId为null的对象,添加匹配到的status属性。

// 构建status映射表,提升匹配效率
const statusMap = new Map(object2.map(item => [item.newEmployeeId, item.status]));

// 遍历处理object1
object1.forEach(obj => {
    if (obj.dependentId === null) {
        const matchedStatus = statusMap.get(obj.employeeId);
        if (matchedStatus) {
            obj.status = matchedStatus;
        }
    }
});

// 输出验证
console.log(object1);

结果说明

  • 处理后object1的结构:
    [
        { name: 'Ben', employeeId: 1, dependentId: null, status: 'Complete' },
        { name: 'Lauren', employeeId: 1, dependentId: 5 },
        { name: 'Jim', employeeId: 2, dependentId: null, status: 'Updating' },
        { name: 'Dan', employeeId: 3, dependentId: null, status: 'Finished' }
    ]
    
  • 使用Map的优势:如果object2数据量较大,Map的O(1)查找性能比每次遍历数组匹配更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:45:46