A better vanilla JS approach to finding any false value in a nested object?
You could take the valus from the object and iterate with a short circuit.
const
hasTrue = object => Object
.values(object)
.some(v => v === false || v && typeof v === 'object' && hasTrue(v)),
object = { field1: { subfield1: true, subfield2: true }, field2: { subfield3: true }, field3: { subfield4: false, subfield5: true } };
console.log(hasTrue(object));
With suggested check object in advance
const
hasTrue = value => value === true || !!value && typeof value === 'object' && Object
.values(value)
.some(hasTrue),
object = { field1: { subfield1: true, subfield2: true }, field2: { subfield3: true }, field3: { subfield4: false, subfield5: true } };
console.log(hasTrue(object));
Here is a simple recursive solution that uses Object.values
,flat
and some
.
function toValues (obj) {
if (typeof obj === 'object') return Object.values(obj).map(toValues);
return obj;
}
const findFalse = obj => toValues(obj).flat().some(v => v === false)
const res = findFalse(obj);
console.log (res);
<script>
const obj = {
field1: {
subfield1: true,
subfield2: true,
},
field2: {
subfield3: true,
},
field3: {
subfield4: false,
subfield5: true,
}
}
</script>
If there's arbitrary nesting, you can't avoid recursion. You can make it cleaner though:
const isObj = obj => obj && typeof obj == "object";
const findFalseRecursively = val => {
if (val === false)
return true;
if (isObj(val))
for (const field in val) {
if (findFalseRecursively(val[field]))
return true;
return false;
}
You could do it by searching inside the string representation of the object like so:
const o = {
field1: {
subfield1: true,
subfield2: true,
},
field2: {
subfield3: true,
},
field3: {
subfield4: false,
subfield5: true,
}
};
const containsFalse = (obj) => /\".+\"\:false[^\"]/.test(JSON.stringify(obj));
console.log(containsFalse(o));
console.log(containsFalse({a:":false"}));
JSON.stringify(...)
is pretty costly though, so I don't know if this is an improvement performance wise.
Update: It is a bit slower than other methods shown here, but if you need something simple it might still be useful. https://jsbench.me/4akcx6gxsn/1