Don P
Don P

Reputation: 63768

More succinct way of checking deep property values

Often when checking if a specific property has a value, you have to traverse some object properties or arrays. This leads to long statements like below, just to avoid an error can't read property ____ of undefined.

Is there a way to write this more succinctly? Possibly ES6 has something? I thought I remember some libraries like Lodash providing helper methods but can't find them.

if (
  user &&
  user.profile.pets &&
  user.profile.pets[0] &&
  user.profile.pets[0].type === "dog"
) {

Upvotes: 1

Views: 51

Answers (1)

alexmac
alexmac

Reputation: 19617

Lodash has two methods: _.has and _.get.

_.has(object, path) checks if path is a direct property of object.

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

let user = {
  profile: {
pets: [{ type: 'dog' }, { type: 'cat' }]
  }
};

// _.has
console.log(_.has(user, 'profile.pets[0].type')); // true
console.log(_.has(user, 'profile.pets[3].type')); // false

// _.get
console.log(_.get(user, 'profile.pets[0].type')); // dog
console.log(_.get(user, 'profile.pets[3].type')); // undefined
console.log(_.get(user, 'profile.pets[3].type', 'unknown')); // unknown
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Upvotes: 2

Related Questions