动态访问对象属性(JS) [英] Dynamically access object propertys (JS)

查看:117
本文介绍了动态访问对象属性(JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用字符串动态访问对象的属性。
例如:
.id.public - > anyObject [id] [public]

I'm trying to access a property of an object dynamically with a string. For example: ".id.public" -> anyObject["id"]["public"]

问题 - 我不喜欢我知道我有多少论据(例如.id或.id.public或.id.public.whatever。

The problem - I don't know how many arguments I have (for example ".id" or ".id.public" or ".id.public.whatever".

我做了一个解决方法:

var currentSplit = anyObject;
var splitted = "id.public".split("\.");
splitted.forEach(function(s) { currentSplit = currentSplit[s]; });

当我现在尝试覆盖对象属性时,我将覆盖引用而不是对象属性。

When I try now to override the object property I will override the reference and not the object property.

currentSplit = "test";

我尝试过像 anyObject [id .public] =test; 但它没有用。

I tried already stuff like anyObject["id.public"] = "test"; but it didn't work.

推荐答案

又一个设置值的方法

function setVal(obj, path, val){
    var paths = path.split('.'),
        curProp = obj;

    for(var i=0;i<paths.length-1;i++){
        curProp = curProp[paths[i]];
    }
    curProp[paths[i]] = val;

}

并使用它

setVal(anyObj, "id.public", 'newValue');

这篇关于动态访问对象属性(JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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