开发者

Javascript object key value coding. Dynamically setting a nested value

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", key2: { nested1: 1, nested2: "wowza!" } };

And I have the following JavaScript function:

var setData = function(path, value) {
    eval("data." + path + "= value;");
};

And in use:

setData("key1", "updated value1"); // data.key1 == "updated value1"
setData("key2.nested1", 99); // data.key2.nested1 == 99

This works, however I would like to accomplish the above without using eval. Is this possible, or is eval the best way to go?

EDIT:

NOTE it can be assumed the value you're setting exists, at least for path de开发者_JS百科pth - 1. I'm more concerned about setting the value of an existing object.


Recursion is what you need:

function setData(key,val,obj) {
  if (!obj) obj = data; //outside (non-recursive) call, use "data" as our base object
  var ka = key.split(/\./); //split the key by the dots
  if (ka.length < 2) { 
    obj[ka[0]] = val; //only one part (no dots) in key, just set value
  } else {
    if (!obj[ka[0]]) obj[ka[0]] = {}; //create our "new" base obj if it doesn't exist
    obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call
    setData(ka.join("."),val,obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj
  }    
}

setData("key1", "updated value1"); // data.key1 == "updated value1"
setData("key2.nested1", 99); // data.key2.nested1 == 99


Yep, it's easy. obj.prop = val is the same as obj['prop'] = val so you can rewrite setData as this:

var setData = function (path, value) {
    data[path] = value;
};

And that should do it.

However, I am not sure how much success you will have with the 3rd level (if that makes sense.) obj.prop.prop can't be referenced by obj['prop.prop'] and will instead have to be referenced by obj['prop']['prop'], so setData would have to be rewritten to take that into account. I'm not having much luck with that, though.

Edit: I have made one that (for me) sets it nested how you want, but no further than that. Unfortunately, if you are nesting deeper than your examples then I don't see a real reason to abandon eval. I have not done any benchmarks, but at some point the calculations will be more computationally expensive than even eval (which is pretty hard to accomplish.)

This is what I came up with, which will set them at least 1 'level' deep; that is, it will work with key2.nested1 but not key2.nested1.i_love_nesting, if that makes sense:

var setData = function (path, value) {
    if (path.indexOf('.') != -1) {
        path = path.split('.');
        for (var i = 0, l = path.length; i < l; i++) {
            if (typeof(data[path[i]]) === 'object') {
                continue;
            } else {
                data[path[i - 1]][path[i]] = value;
            }
        }
    } else {
        data[path] = value;
    }
};

Hope this helps. I might not have written this in the most efficient way, though...


Inspired from @user1416920 I made this one :

function setData(key,val,obj)
{
    keys = key.split(/\./);
    last = keys.pop();

    keys.forEach(function(key)
    {
      if(typeof obj[key] === "undefined")
        obj[key] = {}; 
      obj = obj[key]; 
    });

    obj[last] = val;
}

What it does is pretty self explanatory ^^.


function setData(key,val,obj){
    keys = key.split(/\./);
    to_set = keys.pop();
    keys.forEach(function(obj_name){ obj = obj[obj_name]; });
    obj[to_set] = val;
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜