Created
September 14, 2016 20:33
-
-
Save lwakefield/a1312ac67cccf387e3cfa440496aa2e0 to your computer and use it in GitHub Desktop.
deepget.js
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, 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