JMarsch JMarsch - 2 months ago 8
TypeScript Question

Javascript "deep" check for defined

I could swear that once upon a time, I came across some code that used some js library (maybe lodash??) to do a "deep" check for whether something is defined.

Example:

someLib.isDefined(anObject.aNestedObject.anotherNestedObject);


(would return true if anotherNestedObject is defined, but would return false (and not throw an exception) if anObject or aNestedObject were undefined.

Did I totally dream that, or is there some well-known function out there that does that?

Answer

Lodash's has():

_.has(object, path)

Example:

var object = {a: {b: 'test', c: 'test2'}};
_.has(object, 'a.b');
// => true
_.has(object, 'a.d');
// => false

Full documentation
Source code for _.has()