2

I'm using react and I have state like this

this.state = {
  form: {
    name: {required: true, filled: false, value: ''},
    age: {required: true, filled: false, value: ''},
    dob: {required: false, filled: false, value: ''}
  }
}

I want to check if every form field has been filled, I tried this

const formValid = Object.keys(this.state.form).filter(o=>{
  return o.required
}).every(o=> {
  return o.filled!==null && o.filled!==''
})

I know this is wrong because Object.keys just return the key, I wish the state is array it will make my life much easier, but what if I don't want to change the structure of the state? How do I do it?

3 Answers 3

1

I would use Array#every with Object.keys

With Object.keys you can get the value by referencing the object that it belongs to eg. this.state.form[key]

const formValid = 
  Object.keys(this.state.form)
    .every(key => (
      this.state.form[key].required && 
      this.state.form[key].filled !== null && 
      this.state.form[key].filled !== ''
    ))

if you need a reference to the failures I would change every to filter

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

2 Comments

this make sense too why I keep thinking every is for array only.
it is for an array only. using Object.keys gets the objects keys as an array. then in the every callback we are getting the value from the object explicitly.
1

Use Object.values(this.state.form) instead. This returns an array of the values instead of the keys.

Comments

1

You can map over object keys.

const formValid = Object.keys(this.state.form)
    // map the keys to their values.
    .map(key => this.state.form[key])
    .filter(o => o.required)
    ...

Edit: But if all you want is the values, then the other answer is better.

3 Comments

Why not just Object.values?
@Zlatko what do you mean by slow? so the correct solution should be using Object.values?
Yep. I mean, they are both correct and produce the same result. But Object.values is simpler and shorter.

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.