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

前端 未结 7 920
醉梦人生
醉梦人生 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:35

    This should do the trick

    persons.filter((person) => {
        return person.animals.filter((animal) => {
            return animal.species === 'cat';
        }).length > 0;
    });
    

    Add the check on length, as filter returns an array, not a boolean.

    0 讨论(0)
提交回复
热议问题