Last active
May 9, 2024 19:25
-
-
Save topherPedersen/a433812444c9681f0aa45724a46db8fb to your computer and use it in GitHub Desktop.
Find Property in Nested Object
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
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
fornull
!This condition does not return falsy child values such as
0
,false
and""
:To catch such issues, you can write unit tests where properties have values such as
null
,false
and0
.Object.entries()
is now quite well supported – e.g.: