Instantly share code, notes, and snippets.

Embed
What would you like to do?
function containsInNestedObjectDF(obj, val) {
const stack = [];
stack.push(obj);
while (stack.length > 0) {
const currentObj = stack.shift();
if (currentObj === val) {
return true;
}
const keys = currentObj instanceof Object ? Object.keys(currentObj) : [];
for (const key of keys) {
const objVal = currentObj[key];
stack.unshift(objVal);
}
}
return false;
}
var nestedObject = {
data: {
info: {
stuff: {
thing: {
moreStuff: {
someVal: 40,
something: 'foo2'
}
}
}
}
}
}
let hasIt = containsInNestedObject(nestedObject, 40); // true
let doesntHaveIt = containsInNestedObject(nestedObject, "foo"); // false
console.log(hasIt, doesntHaveIt);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment