白费力气。在概念上看起来很简单,但是JS想要杀了我。
两个对象数组:
let allProfileUsers = [
{
id: "0b4cd920-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
active: true
},
{
id: "0b4f9840-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea73670-31ac-11ec-81f6-9b65b19a8154",
active: true
},
{
id: "0b51e230-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
active: true
}
];
let allAuthUsers = [
{
id: "fea4c570-31ac-11ec-81f6-9b65b19a8154",
username: "user1",
active: true,
},
{
id: "fea73670-31ac-11ec-81f6-9b65b19a8154",
username: "user2",
active: true,
},
{
id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
username: "user3",
active: true,
}
];
我需要比较"id"将第一个数组中对象中的"auth_user_id"字段。基本上,数组1中的所有用户都应该存在于数组2中,基于这两个字段的匹配。
这不起作用(不是简写,所以很容易调试):
let allMatched = allAuthUsers.every(x => {
return allProfileUsers.some(pu => {
return x.id === pu.auth_user_id;
});
});
…返回false;
当然,我可以手动遍历每个值并比较它们。我不想那样,除非没有别的办法。
我不得不认为JS能够提供更优雅的带有箭头的一行代码。事实上,令人沮丧的是,我知道我以前也这样做过,但我今天似乎就是做不到。
伙计,我觉得答案就在你的问题里。你需要先遍历第一个数组(allProfileUsers),然后检查它是否存在于第二个数组(allAuthUsers)。
let allMatched = allProfileUsers.every(pu => {
return allAuthUsers.some(x => {
return x.id === pu.auth_user_id;
});
});
尝试如下内容:将其中一个数组值处理为Set
,并使用另一个数组every
方法。
let allProfileUsers = [
{
id: "0b4cd920-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
active: true,
},
{
id: "0b4f9840-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea73670-31ac-11ec-81f6-9b65b19a8154",
active: true,
},
{
id: "0b51e230-31da-11ec-a31c-cd844bfb73be",
auth_user_id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
active: true,
},
];
let allAuthUsers = [
{
id: "fea4c570-31ac-11ec-81f6-9b65b19a8154",
username: "user1",
active: true,
},
{
id: "fea73670-31ac-11ec-81f6-9b65b19a8154",
username: "user2",
active: true,
},
{
id: "fea98060-31ac-11ec-81f6-9b65b19a8154",
username: "user3",
active: true,
},
];
const auth = new Set(allAuthUsers.map(({ id }) => id));
const isExist = allProfileUsers.every(({ auth_user_id }) =>
auth.has(auth_user_id)
);
console.log(isExist)