gpt4 book ai didi

javascript - 在 JavaScript 中的过滤器内应用过滤器

转载 作者:行者123 更新时间:2023-11-29 16:35:50 24 4
gpt4 key购买 nike

如何在 JavaScript 中的 filter 中应用 filter,同时在数组中查找数组中的值?

比如说,我想要获取团队包括 Jane Smith 的所有建筑项目。

我意识到我在这里发明了一些疯狂的 JavaScript,我只是想向你展示我想要的东西。

const result = myArray.filter(x => x.type === "construction" && x.team.filter(y => y.name.includes("Jane Smith")));

这是我要过滤的数组:

[
{
"type": "construction",
"name": "Project A",
"team": [
{
"name": "John Doe",
"position": "Engineer"
},
{
"name": "Jane Smith",
"position": "Architect"
}
]
},
{
"type": "construction",
"name": "Project B",
"team": [
{
"name": "Walt Disney",
"position": "Creative Director"
},
{
"name": "Albert Einstein",
"position": "Scientist"
}
]
},
{
"type": "remodelling",
"name": "Project C",
"team": [
{
"name": "John Travolta",
"position": "Manager"
}
]
}
]

最佳答案

您可以使用Array#some用于检查团队。

此提案使用 destructuring assignment对于对象。

var array = [{ type: "construction", name: "Project A", team: [{ name: "John Doe", position: "Engineer" }, { name: "Jane Smith", position: "Architect" }] }, { type: "construction", name: "Project B", team: [{ name: "Walt Disney", position: "Creative Director" }, { name: "Albert Einstein", position: "Scientist" }] }, { type: "remodelling", name: "Project C", team: [{ name: "John Travolta", position: "Manager" }] }],
result = array.filter(({ type, team }) =>
type === "construction" && team.some(({ name }) => name === "Jane Smith"));

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

关于javascript - 在 JavaScript 中的过滤器内应用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430908/

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