-
-
Save lydemann/43ab7365bbbc900e32b386a80de98d63 to your computer and use it in GitHub Desktop.
How to find a nested object using breadth first search (recursive) https://jsbin.com/zoxekanoki/edit?html,js,output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function containsInNestedObjectDF(obj, val) { | |
if (obj === val) { | |
return true; | |
} | |
const keys = obj instanceof Object ? Object.keys(obj) : []; | |
for (const key of keys) { | |
const objval = obj[key]; | |
const isMatch = containsInNestedObjectDF(objval, val); | |
if (isMatch) { | |
return true; | |
} | |
} | |
return false; | |
} | |
var nestedObject = { | |
data: { | |
info: { | |
stuff: { | |
thing: { | |
moreStuff: { | |
something: 'foo2', | |
someVal: 40 | |
} | |
} | |
} | |
} | |
} | |
} | |
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