Hi there I am trying to find out if any key value is true of an object.
The following works only for objects without having nested objects.
I am trying to check if any key in the objects no matter parent or child has got true value
const odb = {
"all": true,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": false,
}
}
const isAnyKeyValueTrue = o => !Object.keys(o).find(k => !o[k]);
console.log(isAnyKeyValueTrue(odb));
CodePudding user response:
Check if the value is an object, and if it is, call isAnyKeyValueTrue
again. Also, to be more semantically correct, I have used some
instead of find
. I use && o[k]
to make sure null
is not given to the function (since typeof null === "object"
).
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": { "allF": true },
}
}
const isAnyKeyValueTrue = o => Object.keys(o).some(k => typeof o[k] === "object" && o[k] ? isAnyKeyValueTrue(o[k]) : o[k] === true);
console.log(isAnyKeyValueTrue(odb));
CodePudding user response:
The key point is that if we do not find matched result in current level,then we need to use ||
to find in the children level by invoke the current function recursively
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": false,
'allF':{
'allG':true
}
}
}
const isAnyKeyValueTrue = o => Object.values(o).some(v => ((typeof v == `boolean`) && v) || isAnyKeyValueTrue(v))
console.log(isAnyKeyValueTrue(odb));
CodePudding user response:
const odb = {
"all": false,
"allA": false,
"allB": false,
"allC": {
"allD": false,
"allE": { "allF": true },
}
}
const isTrue = (obj) => {
let result = false;
for (let key in obj) {
if (obj[key] === true) {
result = true;
break;
} else if (typeof obj[key] === 'object') {
result = isTrue(obj[key]);
}
}
return result;
}
console.log(isTrue(odb));