通过点符号字符串在对象文字中设置深度? [英] 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.
这是我想要的执行:
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);
这会将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!
推荐答案
我的版本:
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;
}
工作演示: http://jsfiddle.net/jfriend00/Sxz2z/
这篇关于通过点符号字符串在对象文字中设置深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!