如何仅当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
相关产品推荐
相关产品推荐

