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

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

    Your inner filter still returns a "truthy" value (empty array) for the dog person. Add .length so that no results becomes 0 ("falsey")

    const result = persons.filter(p => p.animals.filter(s => s.species === 'cat').length)

    Edit: Per comments and several other answers, since the goal is to get a truthy value from the inner loop, .some would get the job done even better because it directly returns true if any items match.

    const result = persons.filter(p => p.animals.some(s => s.species === 'cat'))

提交回复
热议问题