I\'m working on a little library that lets me do some basic key value coding with objects. Say I have the following object:
var data = { key1: \"value1\", k
I think this problem becomes easier and more natural to solve if you can be flexible in how you're specifying your path. If instead of doing something like key2.nested1
you can do {key2:{nested1:{}}}
(object notation), it becomes fairly trivial:
function setData(subtree, path){
var nodeName = Object.keys(path);
if(typeof path[nodeName] == 'object')
setData(subtree[nodeName], path[nodeName]);
else
subtree[nodeName] = path[nodeName];
}
var data = { key1: "value1", key2: { nested1: 1, nested2: "wowza!" } };
// For the initial call, 'subtree' is the full data tree
setData(data, {key2:{nested1:99}});
You're simply recursing into the 2nd arg of the setData
call, until you find the value. Each time you recurse, you step down into the data
tree at the specified point.
This function can easily be modified to accept the dot notation you specified, too, but to me this is a cleaner and more natural approach (plus, String ops are slow).
Cheers