gpt4 book ai didi

javascript - 如何在两个对象数组中合并具有相同键的属性?

转载 作者:行者123 更新时间:2023-11-30 07:19:30 25 4
gpt4 key购买 nike

有两个对象数组,其中一些具有相同的键,我想合并第一个数组中的相同键。我已经粘贴了我的代码。我使用了嵌套循环,但性能很差 O(n²)。也许我需要另一种方法来提高性能。(由于某些原因我不能使用 ES6,所以如果是 ES5 方法我将不胜感激。)

var people = [
{
id: "001",
name: "David",
age: 29
},
{
id: "002",
name: "Lucia",
age: 41
},
{
id: "003",
name: "Steve",
age: 18
}
];

var address = [
{
id: "001",
city: "Barcelona"
},
{
id: "002",
city: "Paris"
},
{

},
{
id: "003",
city: "Tokyo"
},
{
id: "004",
city: "Barcelona"
}
];

我的代码

people.forEach(function(item) {
var id = item.id;
address.forEach(function(location) {
if (location.id == id) {
item.address = location.address
}
});
});

结果

var people = [
{
id: "001",
name: "David",
age: 29,
city: "Barcelona"
},
{
id: "002",
name: "Lucia",
age: 41,
city: "Paris"
},
{
id: "003",
name: "Steve",
age: 18,
city: "Tokyo"
}
];

我更喜欢新的 people 数组。

最佳答案

你可以拿一个Map使用所有地址,然后使用 map 的扩展属性映射新对象。

此方法采用address 对象的所有属性。

var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }],
map = new Map(address.map(o => [o.id, o])),
result = people.map(o => Object.assign({}, o, map.get(o.id)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在两个对象数组中合并具有相同键的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56444006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com