swami swami - 3 months ago 8
Javascript Question

javascript render function for objects with missing properties

Our contact record has a phones object, which has 13 possible sub-objects corresponding to the following phone types:

personalMobile1,
personalMobile2,
personalMobile3,
workMobile1,
workMobile2,
workMobile3,
homePhone1,
homePhone2,
homePhone3,
workPhone1,
workPhone2,
workPhone3,
workFax1


I'm trying to write a render function, that will output only numbers (e.g. mobilePhone1.number) which are defined.

Many of these sub-objects may not be present on the returned contact object. This is the maximal possible object.

Suppose I just have 2 sub-objects, then I want output like this:

<p> +91 9883727387 </p>
<p> +91 9736551225 </p>

Answer
If (mobilePhone.hasOwnProperty("number")) {
    // do something here...
}

You can use these sort of conditions within jsx render functions by simply using the && notation

MobilePhone.hasOwnProperty && 
<React-component />

You may be looping through a bunch of contacts, so here is an example:

Contacts.map(function (contactObj) {
   If (contactObj.hasOwnProperty("number") {
      Return <p> { contactObj.number } </p> 
   }
});
Comments