javascript: access object (array) by array notation string

喜你入骨 提交于 2020-01-10 06:06:13

问题


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

1.) there is an object, where

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

(in common case root["obj1"]...["objN"])

2.) I have ONLY string objectPath known:

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

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

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

As I understand

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

  2. 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/

Related Link: Access object child properties using a dot notation string


回答1:


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;
}

You use it like this :

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

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

Demonstration (open the console to see the changed root object)



来源:https://stackoverflow.com/questions/16564027/javascript-access-object-array-by-array-notation-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!