1

I'm aware that api team is the one responsible for sending correct data to the client that requested the data. However, I still would like to know the best way of checking if property exists or not.

// when state property is missing from the api response
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
}

or

// or when birtdate is missing
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555',
    state    : 'MN'
  }
}

or

// when addressInfo is missing
myObject = {
  name : 'Scott',
  birthDate : '20000101'
}

Is the code below enough for the checking?

if (myObject.addressInfo !== undefined && myObject.addressInfo.state !== undefined) {

    // console.log(
}
devwannabe
  • 3,160
  • 8
  • 42
  • 79
  • `if (myObject.addressInfo) ...` returns a boolean, so if it's not on the object it returns false; no need to do a further check for `myObject.addressInfo.state` if the parent doesn't exist. – Data Aug 29 '15 at 03:19

3 Answers3

1

state value could be set as undefined though still be a property of myObject ; try utilizing Object.hasOwnProperty(property)

var myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
};

console.log(myObject.addressInfo.hasOwnProperty("state"))
guest271314
  • 1
  • 15
  • 104
  • 177
1

If you are willing to use a library like lodash or underscore, then a very convenient way to test if a key is present in an object is the _.has method:

var x = { "a": 1 };
_.has(x,"a"); //returns true
_.has(x,"b"); //returns false
zayquan
  • 7,544
  • 2
  • 30
  • 39
  • using _.has(), how will you check state property? Like this? _.has(myObject, 'addressInfo.state') – devwannabe Aug 29 '15 at 03:39
  • Like this : `_.has(myObject.addressInfo, 'state')`. In your case myObject.addressInfo is the object being inspected, and 'state' is the key that you are checking. – zayquan Aug 29 '15 at 03:42
0

Right way to check proerty exists:

if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

and

if(myProp in myObj){
    alert("yes, i have that property");
}

From answer: check if object property exists - using a variable

Community
  • 1
  • 1