javascript: access object (array) by array notation string

我与影子孤独终老i 提交于 2019-11-29 18:14:15

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)

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