0

Let's consider a scenario in the below example, where I want to check the value of the object x.a.b or x.a.b.c, but it is throwing an exception while trying to access the object at second level (x.a.b) 'Uncaught TypeError: Cannot read property 'b' of undefined'.

Ultimately I want to access x.a.b.c, and how can I check if the value is not 'undefined' or 'null' using lodash? Is there a way to check the object in a series of values?

var x = {}
!_.isUndefined(x); // true
!_.isUndefined(x.a); // false
!_.isUndefined(x.a.b); // Uncaught TypeError: Cannot read property 'b' of undefined
Sarvesh Mahajan
  • 914
  • 7
  • 16

1 Answers1

3

Use lodash's _.get() to get the suspected path. It will return undefined or a default value, if the parts of the path don't exist.

Note: if you want to catch null, and undefined use _.isNil() instead of _.isUndefined().

var x = {}
console.log(!_.isUndefined(x)); // true
console.log(!_.isUndefined(_.get(x, 'a'))); // false
console.log(!_.isUndefined(_.get(x, 'a,b')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Another option is the optional chaining which as stage 4 ES proposal (not supported by browsers, but can be enabled with Babel):

var x = {}
console.log(!_.isUndefined(x)); // true
console.log(!_.isUndefined(x?.a)); // false
console.log(!_.isUndefined(x?.a?.b));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209