如何在JavaScript中的filter
中应用filter
,同时在数组中查找数组中的值?
说,我想获得团队中包括construction
的所有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"
}
]
}
]
答案 0 :(得分:4)
您可以使用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; }
答案 1 :(得分:1)
也许类似以下内容?
const result = myArray.filter(x => x.type === "construction" && x.team.filter(y => y.name.includes("Jane Smith")).length > 0);
基本上,我只是检查新过滤后的数组长度是否大于0。