If I have an object, such as:
const obj = {
field1: {
subfield1: true,
subfield2: true,
},
field2: {
subfield3: true,
},
field3: {
subfield4: false,
subfield5: true,
}
}
Then I can do a nested for loop to return true if a value is false by doing,
const findFalse = obj => {
for (const field in obj) {
for (const subfield in obj[field]) {
if (!obj[field][subfield]) return true
}
}
}
If this object wasn't nested, it'd be a bit easier, I could do something like,
const findFalse = obj => Object.keys(obj).some(prop => !obj[prop]);
Both approaches don't really suit what I need, because the object can have 2, 3 or more nested properties. I've come up with a recursive way to figure this out, such as:
const isObj = obj => obj && obj.constructor === Object;
const findFalseRecursively = obj => {
for (const field in obj) {
if (isObj(obj[field]))
return findFalseRecursively(obj[field])
if (obj[field] === false)
return true
}
}
But I'm wondering if there's a cleaner or more efficient way of achieving this?
I would expect the function to return the first false value that it sees, and break out of the function/for loop instantly.