I'm trying to write a function that adds an accessor for each nested property in an object. To make this a bit clearer, given object o
, and a string representing a path, I should be able to access the property at that path as a named property:
var o = {
child1: "foo",
child2: {
child1: "bar",
child2: 1
child3: {
child1: "baz"
}
}
};
addAccessors(o);
o["child2.child1"]; // "bar"
o["child2.child2"]; // 1
o["child2.child3.child1"]; // "baz"
Note that the names won't always be as uniform.
Here is what I have so far:
function addAccessors(parent) {
function nestedProps(o, level) {
if (typeof o == "object") {
var level = level || "";
for (p in o) {
if (o.hasOwnProperty(p)) {
if (level && typeof(o[p]) != "object") {
parent[level + "." + p] = o[p];
}
nestedProps(o[p], (level ? level + "." : "") + p);
}
}
}
}
nestedProps(parent);
}
As you can see from this line: obj[level + "." + p] = o[p];
, I am simply adding the values as new properties onto the array.
What I would like to be able to do is add an accessor that retrieves the value from the appropriate property, so that it is "live". To refer to my earlier example:
o["child2.child2"]; // 1
o["child2"]["child2"] = 2;
o["child2.child2"]; // Still 1, but I want it to be updated
Any ideas on how I can accomplish this?