Skip to content

Instantly share code, notes, and snippets.

@chnbohwr
Forked from bbandydd/getNestedValue.js
Created August 29, 2018 03:47
Show Gist options
  • Save chnbohwr/34c7e6dc0a9149d97ba91d2edddcdd20 to your computer and use it in GitHub Desktop.
Save chnbohwr/34c7e6dc0a9149d97ba91d2edddcdd20 to your computer and use it in GitHub Desktop.
get Nested Object value without using if conditions
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