JavaScript中通过对比两个数组创建新数组的实现方案
解决方案:基于嵌套KeyToMatch合并数组对象
需求说明
现有两个数组Arr1和Arr2,需要遍历Arr2的每一项,将其KeyToMatch对象的所有键值对与Arr1中元素的KeyToMatch完全匹配,匹配成功后合并Arr2项与Arr1中对应的项,生成最终数组。
实现思路
- 预处理Arr1:将
Arr1转换为以KeyToMatch的唯一标识为键的Map,避免直接比较对象引用带来的匹配问题。这里可以把KeyToMatch中的Cl、Ro、Ge值拼接成字符串作为唯一键(比如"2-5-1"),实现快速查找。 - 遍历处理Arr2:对
Arr2的每一项生成同样的唯一键,从Map中取出对应的Arr1对象,合并两个对象(保留Arr2的MoreDatas字段,同时添加Arr1的Image、Name字段)。
代码实现
const Arr1 = [ { KeyToMatch: { Cl: 2, Ro: 5, Ge: 1 }, Image: "image.jpg", Name: "example no 1", }, { KeyToMatch: { Cl: 3, Ro: 1, Ge: 2 }, Image: "image2.jpg", Name: "example no 2", }, { KeyToMatch: { Cl: 9, Ro: 2, Ge: 1 }, Image: "image2.jpg", Name: "example no 2", }, ]; const Arr2 = [ { KeyToMatch: { Cl: 3, Ro: 1, Ge: 2 }, MoreDatas: [], }, { KeyToMatch: { Cl: 2, Ro: 5, Ge: 1 }, MoreDatas: [], }, ]; // 构建Arr1的查找Map const arr1Map = new Map(); Arr1.forEach(item => { const { Cl, Ro, Ge } = item.KeyToMatch; const key = `${Cl}-${Ro}-${Ge}`; arr1Map.set(key, item); }); // 遍历Arr2并合并对象 const result = Arr2.map(arr2Item => { const { Cl, Ro, Ge } = arr2Item.KeyToMatch; const key = `${Cl}-${Ro}-${Ge}`; const matchedItem = arr1Map.get(key); return { ...arr2Item, ...matchedItem }; }); console.log(result);
输出结果
执行代码后输出与预期一致:
[ { KeyToMatch: { Cl: 3, Ro: 1, Ge: 2 }, MoreDatas: [], Image: "image2.jpg", Name: "example no 2", }, { KeyToMatch: { Cl: 2, Ro: 5, Ge: 1 }, MoreDatas: [], Image: "image.jpg", Name: "example no 1", }, ];
补充说明
- 如果
KeyToMatch的字段可能变动,可改用Object.values(item.KeyToMatch).join('-')生成唯一键,无需硬编码字段名,适配性更强。 - 若
Arr1中存在多个匹配同一KeyToMatch的项,当前逻辑会保留最后一个匹配项;如需处理多匹配场景,可将Map的值改为数组,再根据需求选择合并规则。
内容的提问来源于stack exchange,提问作者Gaurav Singh
相关产品推荐
相关产品推荐

