0

There is a variable that outputs the result of validation in ReactJS as an array:

console.log(this.state.check); // [account: false, name: true, email: true]

Verification required:

  • if all values in this variable are true - return true
  • if one or more values are not equal to true - return false and one of the elements with the value false

I am new to ReactJS and my code is throwing an error

var check = this.state.check.map(item => item).some(item => item === true) ? true : false;
console.log(check); // error

I will be very grateful for the correct solution.

2
  • [account: false, name: true, email: true] isn't an array and is invalid. Did you mean { account: false, name: true, email: true }? Commented Jul 3, 2021 at 16:46
  • 1
    V8 will output "[account: false, name: true, email: true]" for let arr = []; arr.account = false; arr.name = true; arr.email = true; console.log(arr);. However, this means the code producing the "array" is severely borked already. Commented Jul 3, 2021 at 16:48

1 Answer 1

2

You need the Array.prototype.filter function:

// Filter the array and get only the items that are false
// Returns an array of false items or an empty array
var falseProps = Object.entries(this.state.check).filter(([key, value]) => value === false);

// False props is now an array 
if(falseProps.length > 0) {
  // Do something if false
} else {
  // Do something if true
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. It works! How can I deduce one of the elements with value false?
The elements with value false are all inside the falseProps array. You can get all or any of them using the usual array access methods. For example. to get the first element, you'd use falseProps[0].
Thank you. Please help me again. How replace item in [account: false, name: true, email: true] ? This data can be filled in automatically in a different order, but I need to sort it so that first comes 'name', then the 'account' and then the 'email'. How can this be sorted?

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.