javascript for loop over properties in an object

Today at work I was tasked with iterating over a JavaScript (TypeScript) object to find a particular property or key nested somewhere within the object. The tricky part is the object can have infinite nesting, so we don’t know how deep we need to dig to find the needle in the haystack.

I thought someone else may end up needing a solution to this problem, so I decided to write this blog post. I found a StackOverflow article which was pretty helpful, however the author of the answer to that question only posted partial bits of the solution, and didn’t post a complete function.

After a little work on replit.com, I came up with a function that does the job for me. For my use case, I only needed to find one needle in the haystack. If you need to find multiple instances of the same property or key, then you’ll need to re-work my function.

Hope you find this function helpful internet friend!

const originalObject = {
foo: {},
bar: "BAR",
baz: {
a: {},
b: {},
c: {
d: "DDD",
e: "EEE",
f: "FFF",
g: "GGG",
h: "HHH",
i: "III",
j: "JJJ",
k: "KKK",
l: "LLL",
m: "MMM",
n: "NNN",
o: "OOO",
p: "PPP",
}
},
}
function findValueOfPropertyInNestedObject(obj: Object, propertyName: string) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const valueOfProperty = obj[prop];
const valueOfPropertyIsObject = typeof valueOfProperty === "object";
const propertyFound = prop === propertyName;
if (propertyFound) {
return valueOfProperty;
}
if (valueOfPropertyIsObject) {
const childValue = findValueOfPropertyInNestedObject(valueOfProperty, propertyName);
if (childValue) {
return childValue;
}
}
}
}
return undefined;
}
const p = findValueOfPropertyInNestedObject(originalObject, "p");
console.log(p);
 

topherPedersen