Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively check object field (+ nested) to be true

Tags:

javascript

I have that object :

obj = {
    a: true,
    b: {
        c: false,
        d: true
    }

What's the best way to check if all fields of my object is set to true. In case all fields are true => result should be true, if not => false.

like image 273
Toto NaBendo Avatar asked Sep 12 '25 19:09

Toto NaBendo


2 Answers

This solution recursively checks if all the values are truthy.

const obj = {
  a: true,
  b: {
    c: false,
    d: true
  }
}

const checkRecursive = (obj) => {
  return Object.values(obj).every(el => typeof el === "object" ? checkRecursive(el) : el); 
}

console.log(checkRecursive(obj));
like image 116
Karim Avatar answered Sep 14 '25 08:09

Karim


Try this.

let obj = {
  a: true,
  b: {
    c: false,
    d: true
  }
};

let objArray = []
function validate(obj) {
    for(const item in obj) {
        if(typeof obj[item] === 'object') {
            validate(obj[item]);
        } else  {
            objArray.push(obj[item]);
        }
    }
}

validate(obj);
// Use filter to check if there are any false value.
console.log(objArray.filter( item => !item).length === 0);
like image 30
Sohail Ashraf Avatar answered Sep 14 '25 09:09

Sohail Ashraf