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?

有帮助吗?

解决方案

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

其他提示

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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top