gpt4 book ai didi

javascript - 合并两个对象数组并跳过具有相同 ID 属性的对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:56:58 33 4
gpt4 key购买 nike

我想合并两个对象数组,但我想跳过具有相同 ID 的对象(我只想保存具有相同 ID 的第一个对象)。

一个数组存储在本地,另一个我从 API 获取用户。

const localUsers = [
{
"id": 1,
"first_name": "Adam",
"last_name": "Bent",
"avatar": "some img url"
},
{
"id": 2,
"first_name": "New Name",
"last_name": "New Last Name",
"avatar": "some new img url"
}

];

const apiUsers = [
{
"id": 2,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "some img url"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "some img url"
}
];

我希望得到这个。 apiUsers中id为2的对象被跳过,因为他已经存在于localUsers对象数组中。我想对具有相同 ID 的所有对象执行此操作。

const mergedUsers = [
{
"id": 1,
"first_name": "Adam",
"last_name": "Bent",
"avatar": "some img url"
},
{
"id": 2,
"first_name": "New Name",
"last_name": "New Last Name",
"avatar": "some new img url"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "some img url"
}

];

最佳答案

创建你的 mergedUsers 连接 localUsers 和已经不在 localUsers 中的 apiUsers:

const localUsers = [
{
"id": 1,
"first_name": "Adam",
"last_name": "Bent",
"avatar": "some img url"
},
{
"id": 2,
"first_name": "New Name",
"last_name": "New Last Name",
"avatar": "some new img url"
}

];

const apiUsers = [
{
"id": 2,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "some img url"
},
{
"id": 3,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "some img url"
}
];

const mergedUsers = localUsers.concat(apiUsers.filter(a => !localUsers.find(b => b.id === a.id)));
console.log(mergedUsers);

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

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