Last active
August 30, 2018 03:37
-
-
Save bbandydd/3f06875cf26293993533f67fb6eadc28 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 = { | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome