Angular 8中如何匹配两数组数据并生成含状态的新数组
需求:根据FactoryId匹配合并两个数组的状态字段
现有如下两个数组,需要遍历array1中的所有factoryId,检查其是否存在于array2中。若array1的factoryId与array2的FactoryId匹配,则将array1的对应对象与array2的Status字段合并,生成新的结果数组。
原始数据
const array1 = [ { "name": "Africa", "filterChildren": [ [ { "name": "Agbara - Laundry", "factoryId": "R_X001" }, { "name": "Agbara - Savoury", "factoryId": "R_X002" } ] ] }, { "name": "X-Ekaterra", "filterChildren": [ [ { "name": "Agbara - Tea", "factoryId": "R_x903" } ] ] } ]; const array2 = [ { "FactoryId": "R_X001", "Status": "Draft" }, { "FactoryId": "R_x903", "Status": "Submitted" } ]
预期输出
const expectedResult = [ { "name": "Africa", "filterChildren": [ [ { "name": "Agbara - Laundry", "factoryId": "R_X001", "Status": "Draft" }, { "name": "Agbara - Savoury", "factoryId": "R_X002" } ] ] }, { "name": "X-Ekaterra", "filterChildren": [ [ { "name": "Agbara - Tea", "factoryId": "R_x903", "Status": "Submitted" } ] ] } ];
解决方案
核心思路是先将array2转换为以FactoryId为键的映射表,实现O(1)时间复杂度的状态查找,再逐层遍历array1的嵌套结构,合并匹配到的状态字段。
// 将array2转换为状态映射表,方便快速查找 const statusMap = array2.reduce((map, item) => { map[item.FactoryId] = item.Status; return map; }, {}); // 遍历array1,合并状态字段(不修改原数组) const result = array1.map(region => { // 处理每一组工厂列表 const updatedGroups = region.filterChildren.map(group => { // 处理每个工厂对象 return group.map(factory => { const matchedStatus = statusMap[factory.factoryId]; // 有匹配状态则合并,否则返回原对象的副本 return matchedStatus ? { ...factory, Status: matchedStatus } : { ...factory }; }); }); // 返回新的区域对象 return { ...region, filterChildren: updatedGroups }; }); // 验证结果 console.log(result);
说明
- 映射表优化:用
reduce将array2转为键值对,避免每次查找都遍历整个array2,提升处理效率。 - 不可变性处理:所有层级都使用对象解构
{...obj}生成新对象,不会修改原始数组的引用,避免副作用。 - 层级遍历:针对
array1的嵌套结构(数组→区域对象→二维filterChildren数组→工厂对象),通过三层map完成逐层处理。
内容的提问来源于stack exchange,提问作者Shilpa
相关产品推荐
相关产品推荐

