安全地访问Javascript嵌套对象 [英] Access Javascript nested objects safely

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

问题描述

我有基于json的数据结构,对象包含嵌套对象。为了访问特定的数据元素,我一直在链接对象属性的引用。例如:

I have json based data structure with objects containing nested objects. In order to access a particular data element I have been chaining references to object properties together. For example:

var a = b.c.d;

如果未定义b或b.c,则会失败并显示错误。但是,我希望得到一个值,如果它存在,否则只是未定义。在不检查链中的每个值是否存在的情况下,最好的方法是什么?

If b or b.c is undefined, this will fail with an error. However, I want to get a value if it exists otherwise just undefined. What is the best way to do this without having to check that every value in the chain exists?

我想尽可能保持这种方法的一般性,所以我不喜欢必须添加大量辅助方法,如:

I would like to keep this method as general as possible so I don't have to add huge numbers of helper methods like:

var a = b.getD();

var a = helpers.getDFromB(b);

我也想尽量避免使用try / catch构造,因为这不是错误所以使用try / catch似乎错位了。这是合理的吗?

I also want to try to avoid try/catch constructs as this isn't an error so using try/catch seems misplaced. Is that reasonable?

任何想法?

推荐答案

你可以创建一种基于属性名称数组访问元素的通用方法,该属性名称数组被解释为通过属性的路径:

You can create a general method that access an element based on an array of property names that is interpreted as a path through the properties:

function getValue(data, path) {
    var i, len = path.length;
    for (i = 0; typeof data === 'object' && i < len; ++i) {
        data = data[path[i]];
    }
    return data;
}

然后你可以用以下方式调用它:

Then you could call it with:

var a = getValue(b, ["c", "d"]);

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

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