简体   繁体   English

通过一串点表示法在对象文字中设置深度?

[英]Setting a depth in an object literal by a string of dot notation?

There are plenty of solutions out there to check/access an object literal giving a string of dot notation, but what I need to do is SET an object literal based on a string of dot notation.有很多解决方案可以检查/访问给出一串点符号的对象文字,但我需要做的是根据一串点符号设置一个对象文字。 It is very technical why I need to do this, and if it isn't feasible I will come up with a different solution.为什么我需要这样做是非常技术性的,如果不可行,我会想出一个不同的解决方案。

Here is what I'd like to do:这是我想要做的:

var obj = { 
   'a': 1, 
   'b': 2, 
    'c': { 
      'nest': true 
    } 
};

I'd like a function that would work something like this:我想要一个可以像这样工作的函数:

setDepth(obj, 'c.nest', false);

That would change the obj to this:这会将 obj 更改为:

var obj = { 
   'a': 1, 
   'b': 2, 
    'c': { 
      'nest': false
    } 
};

I've been trying to an hour and haven't been able to come up with a good solution yet.我一直在尝试一个小时,但还没有想出一个好的解决方案。 Another help would be so greatly appreciated!另一个帮助将不胜感激!

My version:我的版本:

function setDepth(obj, path, value) {
    var tags = path.split("."), len = tags.length - 1;
    for (var i = 0; i < len; i++) {
        obj = obj[tags[i]];
    }
    obj[tags[len]] = value;
}

Working demo: http://jsfiddle.net/jfriend00/Sxz2z/工作演示: http : //jsfiddle.net/jfriend00/Sxz2z/

This is one way of doing it:这是一种方法:

function setDepth(obj, path, value) {
    var levels = path.split(".");
    var curLevel = obj;
    var i = 0;
    while (i < levels.length-1) {
        curLevel = curLevel[levels[i]];
        i++;
    }
    curLevel[levels[levels.length-1]] = value;
}

Working demo.工作演示。

I modified Elliot's answer to let it add new nodes if they don't exist.我修改了 Elliot 的答案,让它添加不存在的新节点。

 var settings = {}; function set(key, value) { /** * Dot notation loop: http://stackoverflow.com/a/10253459/607354 */ var levels = key.split("."); var curLevel = settings; var i = 0; while (i < levels.length-1) { if(typeof curLevel[levels[i]] === 'undefined') { curLevel[levels[i]] = {}; } curLevel = curLevel[levels[i]]; i++; } curLevel[levels[levels.length-1]] = value; return settings; } set('this.is.my.setting.key', true); set('this.is.my.setting.key2', 'hello');

Just do it like this:只需这样做:

new Function('_', 'val', '_.' + path + ' = val')(obj, value);

In your case:在你的情况下:

var obj = { 
   'a': 1, 
   'b': 2, 
    'c': { 
      'nest': true 
    } 
};

new Function('_', 'val', '_.c.nest' + ' = val')(obj, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM