1

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

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.