更新JavaScript对象中的嵌套属性 [英] Update nested attributes in a JavaScript object

查看:68
本文介绍了更新JavaScript对象中的嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式将'hello'更改为'hey',该解决方案应该适用于任意数量的嵌套元素(我只使用2个级别来保持简单)。

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

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

我可以访问'data'变量,路径('level1 / level2')和新价值('嘿')。

I have access to the 'data' variable, the path ('level1/level2') and the new value ('hey').

我试图这样做:

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

想法是前往根

target = data

然后1级深

target = data['level1'] 

...继续

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

并修改内容

target = 'hey'

但是当我这样做时,它似乎失去了对原始对象(数据)的引用(target = target ['level2'])。

But it looks like a lose the reference to the original object (data) when I do (target = target['level2']).

我想我可以用路径构建一个字符串,然后对其进行评估:

I guess I can build a string with the path and then evaluate it:

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

是否有一个更好的解决方案,不涉及eval()?

Is there a better solution that dosen't involve eval()?

推荐答案

有两个问题。首先是你在循环中继续使用 data ,这意味着你试图访问顶级键而不是内键。更改 target = data [ parent [i]]; to

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. Change target = data[parents[i]]; to

target = target[parents[i]];

第二个是当你更改变量 target ,你不是要改变数据变量,而是改变 target 。如果你先退出循环一次迭代你可以更新存储为引用的对象:

The second is that when you change the variable target, you're not changing the data variable but target instead. 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';

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

这篇关于更新JavaScript对象中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆