Last active
February 28, 2018 08:19
-
-
Save jossmac/d6e658b93d499a290e8d4d1545e60617 to your computer and use it in GitHub Desktop.
🤞Here's hoping the optional chaining operator lands
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
function get(obj, ...props) { | |
const val = obj[props[0]]; | |
if (props.length === 1 || !val) return val; | |
const rest = props.slice(1); | |
return get.apply(null, [val, ...rest]); | |
} | |
const user = { | |
name: { | |
first: 'joss', | |
last: 'mack' | |
} | |
} | |
console.log(get(user, 'name', 'first')) // 'joss' | |
console.log(get(user, 'address', 'street1')) // undefined (YAY!) | |
console.log(user.address.street1) // Error (Boo!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment