JMarsch
JMarsch

Reputation: 21751

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?

Upvotes: 1

Views: 257

Answers (3)

George Kagan
George Kagan

Reputation: 6124

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()

Upvotes: 1

Jamil
Jamil

Reputation: 939

No there is no well-known function to do this, but you can check it safely in this way:

if (typeof anObject != "undefined"  
&& typeof anObject.aNestedObject != "undefined" 
&& typeof anObject.aNestedObject.anotherNestedObject != "undefined") {
   console.log("defined");
}else{
  console.log("undefined");
}

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164337

As I wrote in my comment I don't think that it's possible.
The expression anObject.aNestedObject.anotherNestedObject is evaluated before the someLib.isDefined function is invoked so an exception will be thrown (if anObject or aNestedObject don't exist) before the function had a chance to do anything.
Maybe if you'd pass it as a string: someLib.isDefined("anObject.aNestedObject.anotherNestedObjec‌​t")

But, it's easy to check that like this:

if (anObject && anObject.aNestedObject && anObject.aNestedObject.anotherNestedObject) {
    ...
}

Or just implement your own function, it's pretty simple:

function exists(obj: any, keys: string | string[]) {
    if (typeof keys === "string") {
        keys = keys.split(".");
    }

    return keys.every(key => {
        if (!obj) {
            return false;
        }

        obj = obj[key];
        return true;
    });
}

(code in playground)

Upvotes: 2

Related Questions