gpt4 book ai didi

javascript - 将项目过滤到数组内的数组中?

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

const personData = {
personList: [
{

personCodes: [
{
code: "001",
desc: "Indian"
}
]
},

{
personCodes: [
{
code: "002",
desc: "Spanish"
}
]
},
{
personCodes: [
{
code: "001",
desc: "Spanish"
},
{
code: "002",
desc: "Spanish1"
},
{
code: "003",
desc: "Spanish2"
}
]
},

{
personCodes: [
{
code: "001",
desc: "Russian"
}
]
},
{
personCodes: [
{
code: "001",
desc: "Spanish"
},
{
code: "002",
desc: "Indian"
},
{
code: "004",
desc: "Japanina"
}
]
},
{
personCodes: [
{
code: "001",
desc: "Spanish"
},
{
code: "004",
desc: "Indian"
},
{
code: "003",
desc: "Japanina"
}
]
},

]
};

const personID = ["001","003"];

const result = personData.personList.filter(role => role.personCodes && role.personCodes.find(group => personID.includes(group.code)));

console.log(result);

以下代码表示带有人员列表的人员数据。每个人列表代表代码。执行代码后,我得到 5 种不同类型的数组,其中包含 personID 数组中的代码。我想要来自数据第三和第六对象的预期结果。有人可以查看并修改代码吗,我已经附上了所需的代码。谢谢

最佳答案

您可以在 personID 上使用 every(),然后在其中使用 find()

const personData = { personList: [ { personCodes: [ { code: "001", desc: "Indian" } ] }, { personCodes: [ { code: "002", desc: "Spanish" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "002", desc: "Spanish1" }, { code: "003", desc: "Spanish2" } ] }, { personCodes: [ { code: "001", desc: "Russian" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "002", desc: "Indian" }, { code: "004", desc: "Japanina" } ] }, { personCodes: [ { code: "001", desc: "Spanish" }, { code: "004", desc: "Indian" }, { code: "003", desc: "Japanina" } ] }, ] };

const personID = ["001","003"];

const result = personData.personList.filter(role =>
role.personCodes && personID.every(x =>
role.personCodes.find(a => x.includes(a.code))
));

console.log(result);

关于javascript - 将项目过滤到数组内的数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55782910/

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