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

查看:26
本文介绍了安全访问 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;
}

然后你可以调用它:

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

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

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