【问题标题】:Applying filter within a filter in JavaScript在 JavaScript 的过滤器中应用过滤器
【发布时间】:2018-07-19 20:04:32
【问题描述】:

如何在 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"
         }
      ]
   }
]

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用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; }

    【讨论】:

    • 我认为应该是name === "Jane Smith" 而不是name.includes("Jane Smith")。除非我们想匹配,例如“Jane Smithers”。
    • 这看起来非常漂亮和干净——在@thesilkworm 的建议下。我正在测试它。一旦我确定它工作正常,我会接受你的和答案。谢谢!
    • 工作精美,结构易于理解。谢谢!
    【解决方案2】:

    可能类似于以下内容?

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2018-12-09
      • 1970-01-01
      • 2014-05-24
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多