代码之家  ›  专栏  ›  技术社区  ›  Sam

在javascript中的过滤器中应用过滤器

  •  2
  • Sam  · 技术社区  · 6 年前

    我怎么申请 filter 滤波器 在javascript中查找数组中的值?

    说,我想得到所有 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"
             }
          ]
       }
    ]
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   Nina Scholz    6 年前

    你可以用 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; }
        2
  •  1
  •   Charlie Fish    6 年前

    可能是像下面这样?

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

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