javascript - 安全地访问 Javascript 嵌套对象

标签 javascript node.js

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

var a = b.c.d;

如果 b 或 b.c 未定义,这将失败并出现错误。但是,如果它存在,我想获得一个值,否则只是未定义。无需检查链中的每个值是否都存在的最佳方法是什么?

我希望尽可能保持这种方法的通用性,这样我就不必添加大量的辅助方法,例如:

var a = b.getD();

var a = helpers.getDFromB(b);

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

有什么想法吗?

最佳答案

ECMAScript2020 ,并且在 Node v14 中,具有 optional chaining运算符(我见过它也称为安全导航运算符),这将允许您的示例编写为:

var a = b?.c?.d;

来自 MDN docs :

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

关于javascript - 安全地访问 Javascript 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18178406/

相关文章:

javascript - Chartjs 不更新工具提示上的数据集标签

javascript - 升级 Node JS 和 ERR_REQUIRE_ESM : Must use import to load ES Module: 'inheritsloose.js' of Babel Runtime

javascript - 使用 jQuery 导航函数数组

Javascript - 识别正 0 和负 0 数

javascript - 使用循环的 Node js 和 ejs

javascript - 为什么node.js可以在if语句中调用cluster.fork()?

node.js - 如何等待发货完成后再从商店挑选。 Ngrx相关问题

javascript - Node 如何全局访问对象

javascript - 使用搜索功能访问 json

javascript - 下载适用于所有浏览器的 PDF