How to deep check for “null” or “undefined” with JS?

半城伤御伤魂 提交于 2019-12-10 21:46:29

问题


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"
      }
    }       
  }
}

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.

This leads to code like

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

Only checking for

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?


回答1:


From the console in your project directory, npm install dotty

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

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

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

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

See https://www.npmjs.org/package/dotty




回答2:


Another alternative, since a lot of developers already use Lodash, is Lodash's get() method:

import _ from 'lodash';

let data = {
  info: {
    user: {
      email: 'user.email@example.com'
    }
  }
};

_.get(data, 'info.user.email');
// => 'user.email@example.com'


A nice thing about get() is that it supports a default value for cases where the resolved value is undefined:

_.get(data, 'info.user.emailAddress', 'default.email@example.com');
// => 'default.email@example.com'


来源:https://stackoverflow.com/questions/23335580/how-to-deep-check-for-null-or-undefined-with-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!