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
there might options eval(), gets value, not variable;
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.
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.
Comments
Post a Comment