Skip to content

Instantly share code, notes, and snippets.

@lwakefield
Created September 14, 2016 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lwakefield/a1312ac67cccf387e3cfa440496aa2e0 to your computer and use it in GitHub Desktop.
Save lwakefield/a1312ac67cccf387e3cfa440496aa2e0 to your computer and use it in GitHub Desktop.
deepget.js
function get (obj, key, fallback=undefined) {
const keyPath = key.split('.')
try {
return keyPath.reduce((obj, key) => {
if (!(key in obj)) throw new TypeError()
return obj[key]
}, obj)
} catch (e) {
return fallback
}
}
console.log(get({a: 1}, 'a'))
console.log(get({a: 1}, 'b', 2))
console.log(get({a: {b: {c: 1}}}, 'a.b.c'))
console.log(get({a: {b: {c: 1}}}, 'a.b.c'))
const foo = {a: {b: {c: 1}}}
const b = get(foo, 'a.b')
b.c = 2
console.log(foo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment