Check if object properties exist

var pets = { 
  "cats": { 
    "persian": {
      "black": 1,
      "white": 2,
    }, 
    "sphynx": {
      "blue": 2,
      "white": 2,
    }
  },
  "dogs": {
    "pug": {
      "black": 1,
      "brown": 2,
      "white": 1,
    },
    "bulldog": {
      "brown": 1,
      "white": 1,
    }
  }
}
if(pets.persian.black){
  //This might throw an exception if persian does not exist. Error: black of undefined
}

 

Solution with lodash:

_.get(pets, ‘persian.black’)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s