-
-
Save chnbohwr/34c7e6dc0a9149d97ba91d2edddcdd20 to your computer and use it in GitHub Desktop.
get Nested Object value without using if conditions
This file contains hidden or 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 obj = { | |
a: { | |
b: { | |
d: 2 | |
}, | |
c: { | |
e: 5 | |
} | |
} | |
}; | |
const func = (obj, props) => | |
props.reduce((acc, val) => (acc && acc[val]) ? acc[val] : undefined, obj); | |
Object.prototype.getNestedValue = function(props) { | |
return props.reduce((acc, val) => (acc && acc[val]) ? acc[val] : undefined, this); | |
} | |
console.log(func(obj, ['a', 'b', 'd'])); // 2 | |
console.log(obj.getNestedValue(['a', 'c', 'e'])); // 5 | |
console.log(obj.getNestedValue(['a', 'f', 'e'])); // undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment