如何深入检查“null"或“未定义"用JS? [英] How to deep check for "null" or "undefined" with JS?

查看:47
本文介绍了如何深入检查“null"或“未定义"用JS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Node.JS 项目中,假设我有来自 API 或任何其他具有类似结构的对象的响应

In a Node.JS project, let's say I have a response from an API or any other object with a structure like

{
  data: {
    info: {
      user: {
        name: "Hercules",
        password: "Iamthegreatest!"
        email: "hercules@olymp.gr"
      }
    }       
  }
}

访问对象的成员非常容易.但是,在访问任何值之前检查是否存在会得到 PITA.

Accessing the members of the object is pretty easy. However, checking the existence before accessing any value gets PITA.

我可以假设数据始终存在.信息、用户、姓名、密码和电子邮件可能存在,也可能不存在.可以存在没有用户的有效信息对象,也可以存在没有电子邮件地址的有效用户.

I can assume that data is always present. Info, user, name, password and email may be present or may not. There can be a valid info object without an user and there can be a valid user without an email address.

这会导致类似的代码

if (data && data.info && data.info.user && data.info.user.email) {
  var email = data.info.user.email;
}

只检查

if (data.info.user.email)
  // do something
}

如果任何对象不存在,则抛出错误.

Throws an error if any of the objects do not exist.

是否有更短的方法来深入检查此类结构的存在?

Is there a shorter way to deep check the existence of structures like this?

推荐答案

从项目目录中的控制台,npm install dotty

From the console in your project directory, npm install dotty

然后在代码的顶部,使用以下命令导入 dotty:var dotty = require('dotty')

Then at the top of your code, import dotty with: var dotty = require('dotty')

那么如果obj是上面贴出的对象,就可以调用

then if obj is the object posted above, you can call

dotty.exists(obj, "data.info.user.email")

它会产生 truefalse 而不是抛出错误.

and it will yield true or false instead of throwing an error.

参见 https://www.npmjs.org/package/dotty

这篇关于如何深入检查“null"或“未定义"用JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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