Object nested property access

2019-07-13 15:52发布

问题:

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?

回答1:

This is not possible with browsers that are in use nowadays. There is no way to assign a callback or similar to the assignment. Instead use a function to fetch the value in real time:

o.get=function(path)
{
    var value=this;
    var list=path.split(".");
    for (var i=0; i<list.length; i++)
    {
        value=value[list[i]];
        if (value===undefined) return undefined;
    }
    return value;
}
o.get("child2.child1");