2

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?

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.