本文介绍了对象嵌套属性访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个为对象中每个嵌套属性添加访问器的函数.为了更清楚一点,给定对象o和代表路径的字符串,我应该能够以该命名属性访问该路径处的属性:

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);
}

您可以从以下行中看到:obj[level + "." + p] = o[p];,我只是将这些值作为新属性添加到数组中.

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?

推荐答案

对于当今使用的浏览器来说,这是不可能的.无法分配回调或类似于分配的方法.而是使用函数实时获取值:

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");

这篇关于对象嵌套属性访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:24