Javascript object key value coding. Dynamically setting a nested value

后端 未结 5 828
时光取名叫无心
时光取名叫无心 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:38

    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...

提交回复
热议问题