Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Last active May 9, 2024 19:25
Show Gist options
  • Save topherPedersen/a433812444c9681f0aa45724a46db8fb to your computer and use it in GitHub Desktop.
Save topherPedersen/a433812444c9681f0aa45724a46db8fb to your computer and use it in GitHub Desktop.
Find Property in Nested Object
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);
@rauschma
Copy link

rauschma commented May 9, 2024

Hi! I came here via your blog post: https://topherpedersen.blog/2024/05/09/javascript-for-loop-over-properties-in-an-object/

Watch out: also true for null!

const valueOfPropertyIsObject = typeof valueOfProperty === "object";

This condition does not return falsy child values such as 0, false and "":

if (childValue) {

To catch such issues, you can write unit tests where properties have values such as null, false and 0.

Object.entries() is now quite well supported – e.g.:

for (const [key, value] of Object.entries(myObj)) {
  // ···
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment