首页 > 解决方案 > 以有效的方式合并对象数组

问题描述

我有以下场景,我试图合并两个对象数组。

当前代码有效,但我正在寻找一种更有效的方法。

var constList = [
  { name: "jack", id: "1", designation: "hr" },
  { name: "mary", id: "2", designation: "it" },
  { name: "john", id: "3", designation: "fin" }
]

var apiList = [
  { name: "jack", id: "1", height: "10" },
  { name: "mary", id: "2", height: "20" }
]

var temp = [];

constList.forEach(x => {
  apiList.forEach(y => {
    if (x.id === y.id) {
      temp.push({ ...x,
        ...y
      });
    }
  });
});

console.log(temp);

只有来自 apiList 的匹配元素应该与 constList 合并。

输出是正确的,任何人都可以用最好的方法指导我。

标签: javascriptecmascript-6

解决方案


您的解决方案还可以。只有对于非常大的列表,您才能从创建哈希映射中获得的更好的时间复杂度中受益。例如Map

let constList = [{ name: "jack", id: "1", designation: "hr" },{ name: "mary", id: "2", designation: "it" },{ name: "john", id: "3", designation: "fin" }]
let apiList = [{ name: "jack", id: "1", height: "10" },{ name: "mary", id: "2", height: "20" }]

let map = new Map(constList.map(o => [o.id, o]));
let result = apiList.map(o => ({...map.get(o.id),...o}));

console.log(result);

这假设apiList从来没有任何id发生的事情(这是您在评论中确认的)。constList

这里的时间复杂度是O(n+m),而不是从嵌套循环中得到的O(nm) 。

路口

以上假设您真的想要进行合并。但是,我确实注意到,在您的代码中,您实际上并没有合并两者,而是采用了交叉点。如果那是您真正想要的(交集),那么在上面的代码中颠倒两个数组的角色,如下所示:

let constList = [{ name: "jack", id: "1", designation: "hr" },{ name: "mary", id: "2", designation: "it" },{ name: "john", id: "3", designation: "fin" }]
let apiList = [{ name: "jack", id: "1", height: "10" },{ name: "mary", id: "2", height: "20" }]

let map = new Map(apiList.map(o => [o.id, o]));
let result = [];
for (let o of constList) {
    let match = map.get(o.id);
    if (match) result.push({...o, ...match});
}

console.log(result);


推荐阅读