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.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With