This JS function is intended to retrieve or place a value into an object with the nested keys as a string.
For example
var obj = {a: {b: [4]}};
parse_obj_key(obj, "a.b.0") should equal 4.
parse_obj_key(obj, "a.c", 2) should add another element to "a" named "c" with value 2.
The method works, but I'd like to clean it up if possible (or a more polished implementation which is publicly available). I'd also love to know of any edge-case failures which can be found.
function parse_obj_key(obj, loc, val){
var _o = obj;
while (true){
var pos = loc.indexOf('.');
if (!_o || typeof _o != 'object'){
$.log("Invalid obj path: " + loc + "\n" + JSON.stringify(obj));
return null;
}
if (pos === -1){
if (val){
_o[loc] = val;
return obj;
} else {
if (!isNaN(parseInt(loc)))
loc = parseInt(loc);
return _o[loc];
}
}
var part = loc.substring(0, pos);
var loc = loc.substring(pos + 1);
if (!isNaN(parseInt(part)))
part = parseInt(part);
if (!(part in _o)){
if (val)
_o[part] = new object;
else
return null;
}
_o = _o[part];
}
}