Skip to content

Instantly share code, notes, and snippets.

@bbandydd
Last active August 30, 2018 03:37
Show Gist options
  • Save bbandydd/3f06875cf26293993533f67fb6eadc28 to your computer and use it in GitHub Desktop.
Save bbandydd/3f06875cf26293993533f67fb6eadc28 to your computer and use it in GitHub Desktop.
get Nested Object value without using if conditions
const obj = {
class: {
stu1: {
name: 'Andy'
},
stu2: {
name: 'John'
}
}
};
Object.prototype.getNestedValue = function(props) {
return props.reduce((acc, val) => (acc && acc[val]) ? acc[val] : undefined, this);
}
console.log(obj.getNestedValue(['class', 'stu1', 'name'])); // Andy
console.log(obj.getNestedValue(['class', 'stu3', 'name'])); // undefined
@chnbohwr
Copy link

awesome

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