dopplesoldner
dopplesoldner

Reputation: 9469

javascript - check if object has child property

Assuming an object like this

var a = {
  b: {
    c: [
      {
        e: 'hello'
      },
      {
        f: 'bye'
      }
    ]
  }
};

I want to check if e is valid.

Currently I am using multiple if conditions like

if (typeof a !== 'undefined' && typeof a.b !== 'undefined' && typeof a.b.c !== 'undefined' && typeof a.b.c[0] !== 'undefined') {
      console.log('value of e ' + a.b.c[0].e);
}

Is there a cleaner way to achieve the same result?

Thanks

Upvotes: 1

Views: 1290

Answers (1)

ymutlu
ymutlu

Reputation: 6715

I am not sure what you are trying but you can use this to make sure there is "e" value

a = a || {};
var e = a && a.b && a.b.c && a.b.c[0] && a.b.c[0].e;

or you can use

a = a || {};
if (a && a.b && a.b.c && a.b.c[0] && a.b.c[0].e){
   console.log('value of e ' + a.b.c[0].e);
}

if you are sure about values, i like this usage.

var e = a.b.c[0].e || "no value";
// "hello"

var e = a.b.c[0].d || "no value";
// "no value"

Upvotes: 2

Related Questions