javascript - 以有效的方式合并对象数组
问题描述
我有以下场景,我试图合并两个对象数组。
当前代码有效,但我正在寻找一种更有效的方法。
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 合并。
输出是正确的,任何人都可以用最好的方法指导我。
解决方案
您的解决方案还可以。只有对于非常大的列表,您才能从创建哈希映射中获得的更好的时间复杂度中受益。例如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);
推荐阅读
- vba - Access VBA - 如何获取父子窗体的属性,或者获取子窗体的用户给定名称(不是对象引用名称)
- sqlite - NativeScript Vue - VueX 不工作:TypeError:无法读取未定义的属性“状态”
- php - Laravel 8, Sanctum, Fortify /logout 在 Postman 中抛出“CSRF token mismatch”
- azure - 尝试使用第二个自动化帐户在 Azure VM 上添加启动/停止解决方案
- amazon-web-services - AWS Sagemaker Jupyter Notebook 停止打印
- swift - Https 可调用函数 - Firebase
- java - 如何使用 Room 库根据外键在 recyclerview 中显示数据
- laravel - 如何使用 l5-swagger 指定附加属性
- google-chrome-extension - 谷歌浏览器扩展中数组的本地存储
- firebase - 使用 firebase 云消息进行地理定位