简体   繁体   English

更新JavaScript对象中的嵌套属性

[英]Update nested attributes in a JavaScript object

I want to change 'hello' to 'hey' programmatically, the solution should work with any number of nested elements (I just use 2 levels to keep it simple). 我想以编程方式将“ hello”更改为“ hey”,该解决方案应可与任意数量的嵌套元素一起使用(我仅使用2个级别将其保持简单)。

var data = {level1: {level2 : 'hello' }};

I have access to the 'data' variable, the path ('level1/level2') and the new value ('hey'). 我可以访问“数据”变量,路径(“ level1 / level2”)和新值(“ hey”)。

I tried to do: 我试着做:

var parents = 'level1/level2'.split('/');
var target = data;
for(var i=0; i<parents.length; i++){
   target = data[parents[i]];
}
target = 'hey';

The idea was to travel to the root 这个想法是要扎根

target = data

then 1 level deep 然后1级深

target = data['level1'] 

...keep going ...继续

target = data['level1']['level2'] //data['level1'] === target

and modify the contents 并修改内容

target = 'hey'

But it looks like a lose the reference to the original object (data) when I do (target = target['level2']). 但是,当我这样做时,似乎失去了对原始对象(数据)的引用(target = target ['level2'])。

I guess I can build a string with the path and then evaluate it: 我想我可以使用路径构建一个字符串,然后对其进行评估:

eval("data['level1']['level2']='hey');

Is there a better solution that dosen't involve eval()? 是否有一个更好的解决方案,不涉及eval()?

There are two issues. 有两个问题。 First is that you keep using data inside the loop, which means you're trying to access the top level keys instead of the inner keys. 首先是您在循环内继续使用data ,这意味着您尝试访问顶级键而不是内部键。 Change target = data[parents[i]]; 更改target = data[parents[i]]; to

target = target[parents[i]];

The second is that when you change the variable target , you're not changing the data variable but target instead. 第二个是,当您更改变量target ,您并没有更改data变量,而是target If you drop out of the loop one iteration earlier you can update the object which is stored as a reference: 如果您较早退出循环,则可以更新存储为参考的对象:

for(var i=0; i<parents.length-1; i++){
   target = target[parents[i]];
}
target[parents[i]] = 'hey';

Demo: http://jsfiddle.net/Lherp/ 演示: http//jsfiddle.net/Lherp/

Try something like this: 尝试这样的事情:

var data = {level1: {level2 : 'hello' }};
var parents = 'level1/level2'.split('/');
var target = data;
for(var i=0; i < parents.length - 1; i++){
   target = target[parents[i]];
}
target[parents[i]] = 'hey';

Or am I missing something? 还是我错过了什么?

edit: I was missing something (sorry, should have tested it first..) 编辑:我缺少一些东西(对不起,应该先测试一下。。)

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

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