如何向 JSON 对象添加可选链接?

How to add optional chaining to JSON object?

我正在尝试将 JSON 对象中的值与变量进行比较:

if (resp.userdetails.name == username) {
// do something
}

问题是并非所有 resp 对象都有 userdetails,所以我有时会收到此错误消息:

Cannot read properties of undefined (reading 'name')

我曾尝试使用 ? 表示它可能是可选的(或不存在):

if (resp.userdetails?.name == username)

但在那种情况下我得到一个 Unexpected token 错误。

有人可以告诉我如何更新我的 if 语句以说 userdetails 可能并不总是在响应中,但如果是,则检查 name 等于 username?

或者:

  • 使用 JS 引擎which supports optional chaining
  • 使用 Babel 之类的工具将您的 JS 从该语言的现代版本转换为不支持可选链接的旧版本
  • 在尝试从中读取 属性 之前手动测试对象是否存在
if (resp.userdetails && resp.userdetails.name == username)

如果您在项目中安装了lodash,那么您可以使用

_.get(resp,"userdetails.name")

作为documented.

如果你还没有安装 lodash,那么我强烈建议你从 npm 安装,因为 lodash 是最好的也是使用最广泛的实用程序包。

Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on. Lodash can be used directly inside a browser and also with Node.js.

Working with objects using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with them. Lodash comes with lots of features that eases your work with objects.

Lodash is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js.

语法

_.get(object, path, [defaultValue]) Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

Arguments

object (Object) − The object to query.

path (Array|string) − The path of the property to get.

[defaultValue] (*) − The value returned for undefined resolved values.

如果您在项目中安装了lodash,那么您可以使用

_.get(resp,"userdetails.name")

作为documented.

如果您还没有安装 lodash,那么我强烈建议您从 npm 安装,因为 lodash 是最好的也是使用最广泛的实用程序包。

安装 Lodash 的命令

npm install loadash

例如:-

  var _ = require("lodash");

var data = [
  { userdetails: { name: "d" } },
  {},
  { userdetails: {} },
  { userdetails: { name: "d" } },
];

for (i = 0; i < data.length; i++) {
  var resp = data[i];
  if (_.get(resp, "userdetails.name") == "d") {
    //   if (resp.userdetails && resp.userdetails.name == "d") {    use without loadlash
    console.log("Success");
  } else {
    console.log("failed");
  }
}

这里的 loadash 超级复杂。但是您可以使用它来避免运行时错误。下面两个表达式得到相同的结果

   resp.userdetails && resp.userdetails.name == "d"

                        ===

         _.get(resp, "userdetails.name") == "d"