0

I need to access Javascript object property if and if only that property is available.

object.property.anotherInnerProperty ="value"

To access and check above value we normally use following way

if(object && object.property && object.property.anotherInnerProperty=="value")
   then do this

Is there any effective and less code method to access object.property.anotherInnerProperty ?

coding_Lover
  • 393
  • 1
  • 4
  • 13
  • Does this answer your question? [How do I check if an object has a specific property in JavaScript?](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript) – keikai Dec 18 '19 at 07:51
  • Would you mind using `lodash.get` method for this? – Umair Sarfraz Dec 18 '19 at 08:00
  • @coding_Lover what you have done is completely okay to do. Even if there is more code it is most safest approach – AL-zami Dec 18 '19 at 08:02

2 Answers2

3

You can use optional chaining to make your code less verbose:

if(object?.property?.anotherInnerProperty === "value") {
 // then do this
}

Note that this is still a new feature of the language, so you might need some transpiling to make it work in most of the browsers.

Clarity
  • 10,730
  • 2
  • 25
  • 35
0

You can also use lodash.get method:

const object = {
  property: {
    innerProperty: 'foo'
  }
};

const anotherObject = null;

console.log(_.get(object, 'property.innerProperty'));
console.log(_.get(anotherObject, 'property.innerProperty'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Umair Sarfraz
  • 5,284
  • 4
  • 22
  • 38