Javascript object key value coding. Dynamically setting a nested value

后端 未结 5 815
时光取名叫无心
时光取名叫无心 2020-12-15 01:58

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         


        
5条回答
  •  天涯浪人
    2020-12-15 02:56

    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

提交回复
热议问题