Last active
July 2, 2016 13:24
-
-
Save zanona/ba67792b60bf717e1b36eaef4b8ef6a2 to your computer and use it in GitHub Desktop.
Get or Set Object based on literal paths
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
//GET OR SET OBJECTS BASED ON LITERAL PATHS | |
function obj(base, path, value) { | |
const getter = typeof value === 'undefined', | |
nullify = (value === null), | |
keys = path.split(/[\.\[\]]/).filter((i) => i); | |
let key, | |
rBase = base || {}; | |
while ((key = keys.shift())) { | |
if (keys.length) { | |
if (getter || nullify) { | |
rBase = rBase[key] ? rBase[key] : rBase; | |
} else { | |
const isArray = !isNaN([keys[0]]); | |
rBase[key] = rBase[key] || (isArray ? [] : {}); | |
rBase = rBase[key]; | |
} | |
} else { | |
if (getter) { | |
return rBase[key]; | |
} else if (nullify) { | |
delete rBase[key]; | |
} else { | |
return rBase[key] = value; | |
} | |
} | |
} | |
} | |
var base = {foo: 'bar', bar: [{baz: false}]}; | |
//SET | |
obj(base, 'bar[1].baz', 'Object was set'); | |
//GET | |
console.log(obj(base, 'bar[1].baz')); | |
//DELETE | |
obj(base, 'base[1].baz', null); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment