Last active
August 29, 2015 14:20
-
-
Save jasonmit/7e02fd5468bd58d610d6 to your computer and use it in GitHub Desktop.
get({ foo: { bar: 'bar' }}, 'foo.bar');
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
// | |
// https://jsfiddle.net/jmvf41f4/1/ | |
// | |
function get(object, path) { | |
var paths = path.split('.'); | |
var len = paths.length; | |
var out = object; | |
var i = 0; | |
for (;i<len;i++) { | |
out = out[paths[i]]; | |
if (!out && i < (len - 1)) { return; } | |
} | |
return out; | |
} | |
function set(object, path, value) { | |
var paths = path.split('.'); | |
var len = paths.length; | |
var cur = object; | |
var i = 0; | |
for (;i<len;i++) { | |
if (i < (len - 1)) { | |
if (cur[paths[i]] === undefined) { | |
cur[paths[i]] = Object.create(null); | |
} | |
} else { | |
cur[paths[i]] = value; | |
} | |
cur = cur[paths[i]]; | |
} | |
} | |
var a = {}; | |
set(a, 'b.c.d.e.f.g', 'hello world'); | |
console.log(get(a, 'b.c.d.e.f.g') === 'hello world'); | |
console.log(get(a, 'b.c')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment