我想合并两个对象数组,但是我想跳过具有相同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"
}
];
我希望得到这个。 ID为2的apiUsers中的对象被跳过,因为该对象已经存在于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"
}
];
答案 0 :(得分:3)
创建您的mergedUsers
来连接localUser和已经不在localUser中的apiUser:
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);
答案 1 :(得分:1)
您可以通过按所需顺序减少数组来使用Map
。
Lon
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" }],
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" }],
result = Array.from(
[localUsers, apiUsers]
.reduce(
(m, a) => a.reduce((n, o) => n.set(o.id, n.get(o.id) || o), m),
new Map
)
.values()
);
console.log(result);
答案 2 :(得分:1)
首先从apiUsers
中删除localUsers
中存在的所有实例,然后将该数组添加到localUsers
中。数组的顺序与问题中没有提到的无关,但很容易执行。
const filteredApiUsers = apiUsers.filter(x => !localUsers.some(y => x.id === y.id));
const mergedUsers = [...localUsers, ...filteredApiUsers];
答案 3 :(得分:0)
您可以使用它来将两个对象与重复项组合在一起:
Array.prototype.push.apply(localUsers,apiUsers);
然后,您可以使用新对象删除重复项。
答案 4 :(得分:0)
合并两个数组。
let distinctApiUsers = apiUsers
.filter(rUser => localUsers
.findIndex(lUser => lUser.id == rUser.id) == -1)
let mergedArray = localUsers.concat(distinctApiUsers)
答案 5 :(得分:0)
编写自己的比较功能很容易:
for(var i=0; i<localUsers.length; ++i) {
var checked = 0;
for(var j=i+1; j<apiUsers.length; ++j) {
if(localUsers[i]['id'] === apiUsers[j]['id']){
apiUsers.splice(j--, 1);
}
}
}
console.log(localUsers.concat(apiUsers));