解析对象点表示法以检索对象的值 [英] Parse object dot notation to retrieve a value of an object

查看:118
本文介绍了解析对象点表示法以检索对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己正在努力解决一个小问题。
假设我有一个对象:

I'm finding myself struggling with a little problem. Let's say I've got an object:

var foo = {
    bar: {
        baz: true
    }
};

现在我还有一个字符串'foo.bar.baz'。我现在想要使用字符串从对象中检索值。

Now I also have a String 'foo.bar.baz'. I'd now like to retrieve the value from the object using the string.

请注意:这只是一个例子,解决方案需要是动态的。

Please note: This is just an example, the solution needs to be dynamic.

更新:

我还需要变量名称是动态的,并从字符串中解析。此外,我不能确定我的变量是窗口的属性。

I need the variable name also to be dynamic and parsed from the string. Also I can't be sure that my variable is a property of the window.

我已经使用 eval ,但我认为这非常难看:
http://jsfiddle.net/vvzyX/

I have already built a solution using eval, but this is pretty ugly I think: http://jsfiddle.net/vvzyX/

推荐答案

以下是如何做到这一点:

Here is how you can do this:

function getValue(namespace, parent) {
    var parts = namespace.split('.'),
        current = parent || window;
    for (var i = 0; i < parts.length; i += 1) {
        if (current[parts[i]]) {
            current = current[parts[i]];
        } else {
          if (i >= parts.length - 1)
            return undefined;
        }
    }
    return current;
}
var foo = {
    bar: {
        baz: true
    }
};
console.log(getValue('foo.bar.baz')); //true

函数的第一个参数是命名空间(点分隔值),第二个参数是第二个参数是对象,如果未提供父对象,则使用 window

The first argument of the function is the namespace (dot separated values) and the second one is the parent object, if parent is not provided then window is used.

使用父参数的另一个例子:

One more example using the parent argument:

var str = 'foo.bar.baz';
    foo = {
       bar: {
          baz: true
       }
    };

result = getValue(str, foo);
console.log(result);

以下是 jsfiddle

YUI中使用了类似的方法。他们的方法称为命名空间模式。主要好处是模拟包/命名空间。此脚本与命名空间模式之间的唯一区别是命名空间函数创建嵌套结构而不是仅返回值。

Similar approach is used in YUI. Their approach is called Namespace pattern. The main benefit is simulation of packages/namespaces. The only difference between this script and the namespace pattern is that the namespace function creates nested structure instead of only returning value.

这篇关于解析对象点表示法以检索对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆