Álvaro
Álvaro

Reputation: 2588

Run `every` method on array of objects inside arrays of objects

I am trying to check if a property inside this double array has any length

const cars = [
  {
    name: 'audi',
    options: [
      {
        color: 'white'
      },
      {
        color: 'black'
      }
    ]
  },
  {
    name: 'bmw',
    options: [
      {
        color: 'red'
      },
      {
        color: ''
      },
      {
        color: 'green'
      }
    ]
  }
]
const results = cars.map(({ options }) => options.every((opt) => opt.color.length))
const result = !results.includes(false)
console.log(result)
// It returns false cause bmw has an empty color property 

I got it done by adding an array with a boolean for each array with every and then checking for a false on that array, but it feels unnecessary.

Is there a way to return a single boolean if any given property, inside the nested array, has a condition?

Upvotes: 2

Views: 367

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386600

Just take every for the outer array as well.

const
    cars = [{ name: 'audi', options: [{ color: 'white' }, { color: 'black' }] }, { name: 'bmw', options: [{ color: 'red' }, { color: '' }, { color: 'green' }] }],
    result = cars.every(({ options }) =>
        options.every(({ color: { length } }) => length)
    );

console.log(result);

Upvotes: 3

Related Questions