JavaScript的:访问对象(阵列)通过阵列符号串 [英] javascript: access object (array) by array notation string

查看:131
本文介绍了JavaScript的:访问对象(阵列)通过阵列符号串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问对象只提供了它在阵列的形式被称为串路径。

I would like to access the object provided only it's string path in form of array is known.

1)有一个对象,其中

1.) there is an object, where

root["obj1"]["obj2"] = 1;

(在通常情况下根[OBJ1] ... [objN]

2)我只有串objectPath称为:

2.) I have ONLY string objectPath known:

var objectPath = 'root["obj1"]["obj2"]'

3)。我需要的不仅是阅读对象,但设置它的值,如

3.) I need NOT only READ the object, but SET it's value, like

objectPath = 2;
//so root["obj1"]["obj2"] === 2

据我了解


  1. 有可能与eval()函数的一些选项,但它得到的值,而不是变量;

  1. there might be some options with eval(), but it gets the value, not the variable;

通过根的所有事物,可以循环,使皈依到root.obj1.obj2(这是不是这样的,因为OBJ1可以很容易地OBJ与spaces1),并检查是否给定的字符串等于在回路电流对象

one can loop through all objects of root, make convertion to "root.obj1.obj2" (which is not the case, as "obj1" can easily be "obj with spaces1") and check if given string equals to current object in the loop.

http://jsfiddle.net/ACsPn/

相关链接:
<一href=\"http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string\">Access使用点符号的字符串对象子属性

推荐答案

我为你写一个函数,试图使它为pretty和可重复使用尽可能:

I wrote a function for you, trying to make it as pretty and reusable as possible :

function setProp(path, newValue, holder) {
    var t = path.split(/[\[\]"]+/).filter(function(v){return v}),
        l = t.pop(), s, o = holder || window;
    while (s = t.shift()) o = o[s];
    o[l] = newValue;
}

您使用它是这样的:

setProp('root["obj1"]["obj2"]', 2);

如果您的根对象是不是在一个全局变量,通过相关持有人作为第三个参数。

If your root object isn't in a global variable, pass the relevant holder as third argument.

示范(打开控制台来查看更改根对象)

这篇关于JavaScript的:访问对象(阵列)通过阵列符号串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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