0

I have a function that loops through an object that currently returns 5 values. The last value it returns will always be undefined.

I would like to execute some code only if all 4 value.valueId === 2

This is what I have right now

Object.values(answers['3']).forEach(value => {
    console.log('checkboxValues', value.valueId)
    if (value.valueId === 2) {
      console.log('I AM 2')
    } else {
      console.log('I AM SOMETHING ELSE')
    }
  })

How do I check if all value.valueId === 2 ?

3
  • 1
    What is answers[3]? - don't see answers array defined anywhere. Commented Jan 9, 2020 at 21:23
  • answers is an object, the function is executing code on the 3rd nested object that is inside of answers Commented Jan 9, 2020 at 21:24
  • 1
    this is not a a Minimal, Reproducible Example stackoverflow.com/help/minimal-reproducible-example Commented Jan 9, 2020 at 21:26

1 Answer 1

2

Just use 'every'. Info: https://www.w3schools.com/jsref/jsref_every.asp

Object.values(answers['3']).every(value => {
    return value.valueId === 2;
})

Here is it as an if statement:

if (Object.values(answers['3']).every(v => v.valueId === 2)) {
    // do success case
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers bro, didn't know about .every

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.