Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active February 28, 2018 08:19
Show Gist options
  • Save jossmac/d6e658b93d499a290e8d4d1545e60617 to your computer and use it in GitHub Desktop.
Save jossmac/d6e658b93d499a290e8d4d1545e60617 to your computer and use it in GitHub Desktop.
🤞Here's hoping the optional chaining operator lands
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