JavaScript 对象的动态深度设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6842795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic deep setting for a JavaScript object
提问by Alex
Given a string for a object property path, how do I set this property dynamically.
给定对象属性路径的字符串,如何动态设置此属性。
Given this sample object:
鉴于此示例对象:
var obj = {
a: {
b: [ { c: 'Before' } ]
}
};
It should be able to set the value with a helper function like this:
它应该能够使用这样的辅助函数设置值:
setToValue(obj, 'After', 'a.b.0.c');
I tried it with the following code. But parent is a copy if the variable not a reference.
我用下面的代码试过了。但是如果变量不是引用,则 parent 是副本。
function setToValue(obj, value, path) {
var arrPath = path.split('.'),
parent = obj;
for (var i = 0, max = arrPath.length; i < max; i++) {
parent = parent[arrPath[i]];
}
parent = value;
}
回答by Tigraine
a) What's wrong with a simple a.b[0].c = 'After'?
a) 简单的 ab[0].c = 'After' 有什么问题?
As for the method:
至于方法:
function setToValue(obj, value, path) {
var i;
path = path.split('.');
for (i = 0; i < path.length - 1; i++)
obj = obj[path[i]];
obj[path[i]] = value;
}
Here the JSFiddle: http://jsfiddle.net/QycBz/24/
这里是 JSFiddle:http: //jsfiddle.net/QycBz/24/
回答by Dieter Gribnitz
Here is a full solution.
这是一个完整的解决方案。
Also creates objects if they don't exist.
如果对象不存在,也会创建对象。
function setValue(obj, path, value) {
var a = path.split('.')
var o = obj
while (a.length - 1) {
var n = a.shift()
if (!(n in o)) o[n] = {}
o = o[n]
}
o[a[0]] = value
}
function getValue(obj, path) {
path = path.replace(/\[(\w+)\]/g, '.')
path = path.replace(/^\./, '')
var a = path.split('.')
var o = obj
while (a.length) {
var n = a.shift()
if (!(n in o)) return
o = o[n]
}
return o
}
回答by Per Lundberg
FWIW, those of you wishing to the same in CoffeeScript might find these methods handy - it's a quite straight port of the above code. As an extra bonus, they make sure all the objects in the path exists (the getPropertyByPath doesn't throw exceptions if they don't, and the set method will create empty objects if any objects in the path happen to be null).
FWIW,那些希望在 CoffeeScript 中使用相同方法的人可能会发现这些方法很方便——它是上述代码的直接移植。作为额外的奖励,它们确保路径中的所有对象都存在(如果不存在,getPropertyByPath 不会抛出异常,如果路径中的任何对象碰巧为空,则 set 方法将创建空对象)。
getPropertyByPath: (obj, path) ->
path = path.split('.')
parent = obj
if path.length > 1
parent = parent[path[i]] for i in [0..path.length - 2]
parent?[path[path.length - 1]]
setPropertyByPath: (obj, path, value) ->
path = path.split('.')
parent = obj
if path.length > 1
parent = (parent[path[i]] ||= {}) for i in [0..path.length - 2]
parent[path[path.length - 1]] = value