1

I have an array of object

x = [{id: 1, status: false}, {id: 2, status: false}, {id: 3, status: false}]

I want to validate and call a method when all the status is true.

Need help on validating each object.

5 Answers 5

2
const allTrue  = x.every(obj => obj.status === true)
if(allTrue){
 // call your method
 }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.prototype.every for this The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

const valid = x.every(item => item.status === true)
if (valid){
    // CALL THE METHOD YOU WANT 
}

Comments

0

You can do it like this:

   const isAllStatusesTrue = x.every(item => item.status === true);

   if (isAllStatusesTrue) {
       // Some actions
   }

Comments

0

You can do this by writing a validation function using Array's filter function:

const isValid = objects => {
    return objects.filter(el => !el.status).length === 0;
}


// Use your const x:
console.log(isValid(x));

Comments

0

here example:

x = [{id: 1, status: false}, {id: 2, status: false}, {id: 3, status: false}];

function validateStatus(arr){
    for(var i=0;i<arr.length;i++){
        if(!arr[i].status){
            return false;
        }
    }
    return true;
}

console.log(validateStatus(x));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.