Created
September 13, 2013 08:54
-
-
Save adamvr/6548247 to your computer and use it in GitHub Desktop.
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
var resolve = function (key, object) { | |
var split = key.split('.') | |
for (var i = 0; i < split.length; i += 1) { | |
var key = split[i]; | |
if ('undefined' === object[key]) break; | |
object = object[key]; | |
} | |
return object; | |
}; | |
var set = function (key, object, value) { | |
var split = key.split('.') | |
, penultimate = split.slice(0, -1).join('.') | |
, ultimate = split.slice(-1).join('.'); | |
var obj = resolve(penultimate, object); | |
if (obj) { | |
// If we can resolve it, set the value | |
obj[ultimate] = value; | |
} else { | |
// If not, we have to mkdirp | |
mkdirp(penultimate, object); | |
resolve(penultimate, object)[ultimate] = value; | |
} | |
}; | |
var mkdirp = function (key, object) { | |
var split = key.split('.'); | |
if (!object) return; | |
for (var i = 0; i < split.length; i += 1) { | |
var key = split[i]; | |
// For each layer, create a new object if none exists | |
if (!object[key]) object[key] = {}; | |
// And drill down into it | |
object = object[key]; | |
} | |
}; | |
var a = { | |
a: { | |
b: { | |
c: 'd' | |
} | |
} | |
}; | |
console.log(resolve('a.b.c', a)); | |
console.log(a); | |
set('a.c.d', a, {herp: 'derp'}); | |
console.log(a.a.c.d); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment