Created
September 4, 2014 22:29
-
-
Save whayler1/f2796d374b76b2668ae3 to your computer and use it in GitHub Desktop.
create deep values in an object with a string
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
var assert = require('assert') | |
var set = function(obj, key, val) { | |
var split = key.split('.'), | |
prop = obj, | |
prevIndex; | |
//single length key needs no depth traversal | |
if(split.length == 1) { | |
prop[key] = val; | |
return obj; | |
} | |
split.forEach(function(part, index) { | |
var partWithoutIndex, | |
partAryIndex, | |
i = 0, | |
hasIndex = typeof prevIndex === 'number'; | |
if(part.match(/\[.{1,}]/) instanceof Array ) { | |
partAryIndex = parseInt(part.match(/\[(.{1,})]/)[1], 10); | |
partWithoutIndex = part.replace(/\[.{1,}]/, ''); | |
//console.log('partAryIndex:', partAryIndex); | |
//console.log('partWithoutIndex:', partWithoutIndex); | |
if(typeof prop[partWithoutIndex] === 'undefined') { | |
prop[partWithoutIndex] = []; | |
} | |
if(index === split.length - 1) { | |
prop[partWithoutIndex][partAryIndex] = val; | |
}else { | |
prop = prop[partWithoutIndex]; | |
} | |
}else { | |
if(index === split.length - 1) { | |
if(hasIndex) { | |
prop[prevIndex] = {}; | |
prop[prevIndex][part] = val; | |
}else { | |
prop[part] = val; | |
} | |
} else { | |
if(hasIndex) { | |
prop[prevIndex] = {}; | |
if(typeof prop[prevIndex][part] === 'undefined') { | |
prop[prevIndex][part] = {}; | |
} | |
prop = prop[prevIndex][part]; | |
}else { | |
if(typeof prop[part] === 'undefined') { | |
prop[part] = {}; | |
} | |
prop = prop[part]; | |
} | |
} | |
} | |
prevIndex = partAryIndex; | |
}) | |
return obj; | |
}; | |
var res = set({}, 'thing.foo.bar.plop.glop', 'baz'); | |
assert.equal(res.thing.foo.bar.plop.glop, 'baz'); | |
var res = set({}, 'justin[1].foo', 'meow'); | |
assert.equal(res.justin[1].foo, 'meow'); | |
var res = set({}, 'justin[12].foo.gloob', 'meow'); | |
assert.equal(res.justin[12].foo.gloob, 'meow'); | |
var res = set({}, 'justin[12].foo.gloob[3]', 'rarara'); | |
assert.equal(res.justin[12].foo.gloob[3], 'rarara'); | |
var res = set({}, 'justin[12].foo.gloob[3].za', 'rarara'); | |
assert.equal(res.justin[12].foo.gloob[3].za, 'rarara'); | |
var res = set({}, 'justin[12].foo.gloob[3][4][2].za', 'rarara'); | |
assert.equal(res.justin[12].foo.gloob[3].za, 'rarara'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment