2

在数组中查找数组中的值时,如何在 JavaScript 中应用filterfilter

说,我想获得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"
         }
      ]
   }
]
4

2 回答 2

4

你可以Array#some用来检查团队。

该提议对对象使用解构赋值

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; }

于 2018-07-19T20:09:07.510 回答
1

也许像下面这样?

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

基本上我只是检查新的过滤数组长度是否大于 0。

于 2018-07-19T20:07:45.910 回答