jquery - javascript: access object (array) by array notation string -


i access object provided it's string path in form of array known.

1.) there object, where

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

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

2.) have string objectpath known:

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

3.) need not read object, set it's value, like

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

as understand

  1. there might options eval(), gets value, not variable;

  2. one can loop through objects of root, make convertion "root.obj1.obj2" (which not case, "obj1" can "obj spaces1") , check if given string equals current object in loop.

http://jsfiddle.net/acspn/

related link: access object child properties using dot notation string

i wrote function you, trying make pretty , reusable 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 :

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

if root object isn't in global variable, pass relevant holder third argument.

demonstration (open console see changed root object)


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -