Given a JS object
var obj = { a: { b: \'1\', c: \'2\' } }
and a string
\"a.b\"
how can I convert the stri
At the risk of beating a dead horse... I find this most useful in traversing nested objects to reference where you're at with respect to the base object or to a similar object with the same structure. To that end, this is useful with a nested object traversal function. Note that I've used an array to hold the path. It would be trivial to modify this to use either a string path or an array. Also note that you can assign "undefined" to the value, unlike some of the other implementations.
/*
* Traverse each key in a nested object and call fn(curObject, key, value, baseObject, path)
* on each. The path is an array of the keys required to get to curObject from
* baseObject using objectPath(). If the call to fn() returns falsey, objects below
* curObject are not traversed. Should be called as objectTaverse(baseObject, fn).
* The third and fourth arguments are only used by recursion.
*/
function objectTraverse (o, fn, base, path) {
path = path || [];
base = base || o;
Object.keys(o).forEach(function (key) {
if (fn(o, key, o[key], base, path) && jQuery.isPlainObject(o[key])) {
path.push(key);
objectTraverse(o[key], fn, base, path);
path.pop();
}
});
}
/*
* Get/set a nested key in an object. Path is an array of the keys to reference each level
* of nesting. If value is provided, the nested key is set.
* The value of the nested key is returned.
*/
function objectPath (o, path, value) {
var last = path.pop();
while (path.length && o) {
o = o[path.shift()];
}
if (arguments.length < 3) {
return (o? o[last] : o);
}
return (o[last] = value);
}