JS (ES6): Filter array based on nested array attributes

前端 未结 7 918
醉梦人生
醉梦人生 2020-12-20 17:48

I have an array, which looks like this:

const persons = [
  {
    name: \"Joe\",
    animals: [
      {species: \"dog\", name: \"Bolt\"},
      {species: \"c         


        
7条回答
  •  囚心锁ツ
    2020-12-20 18:16

    You havent checked against the length of the second filter.

    Filer only includes results that return a true value. So we need to provide the second filter with a way of returning true if it finds something. We can do that by saying, if the returned array is > 0

    const persons = [
      {
        name: "Joe",
        animals: [
          {species: "dog", name: "Bolt"},
          {species: "cat", name: "Billy"},
        ]
      },
      {
        name: "Bob",
        animals: [
          {species: "dog", name: "Snoopy"}
        ]
      }
    ];
    
    const filtered = persons.filter(p => p.animals.filter(a => a.species === "cat").length > 0)
    
    console.log(filtered)

提交回复
热议问题