Accessing nested JavaScript objects with variables -
I want to use (get / set) a nested JS object with a variable.
For example, static will look like this:
$ obj.children.12.children.32.Name; // Returns "Foo"
Now I have a "root" array (or whatever is easy, it also handles):
[ "Children", 12, "children", 32, "name"]
and want to get the value of the object.
As I read on staxover, there is a very easy way of doing this (solution 2).
But, now I want to change the value for the key / path passed.
Edit: I can use jQuery / Anglo-FEATURES, if it helps me
, we can make a waiter from Triveni:
function getFromPath (obj, pathArray) {var res = obj; For (var i = 0; i & lt; pathArray.length; i ++) {res = res [PathAre [i]]; } Return Ridge; }
We call it with getFromPath ($ obj, ["children", 12, "children", 32, "name"]);
.
Since you want to convert this eclipse function into setter, you want to set a property on the second-to-last object. We can do such a loop by stopping a repetition and then by setting the object with the last property name:
function set-up (obj, pathArray, valueToSet) {var res = obj; // note 'length - 1' here: we do not go to the end of the path for (var i = 0; i & lt; pathArray.length - 1; i ++) {res = res [pathAre [i]]; } // res is now the last thing in the path from the second, // and we will set the last value as the last property on the object var = pathArray [pathArray.length-1]; Res [finalKey] = valueToSet; }
We call it with setToPath ($ obj, ["children", 12, "children", 32, "name"], "pimple");
.
Alternatively, if you want to do it with only one waiter, you can shorten your path in one way and set the result to result:
< Pre> Variable Second Taillight = Duffuffpath ($ obj, ["children", 12, "kids", 32]); Second search ["name"] = "dana";
Comments
Post a Comment