1

How would I make this append only if telephone exists and skip if telephone doesn't exist

for (var i in data.businesses) {
    $('body').append( "<p>" + data.businesses[i].telephone + "</p>");
}
Jesse
  • 8,605
  • 7
  • 47
  • 57
Dasa
  • 297
  • 1
  • 7
  • 23
  • possible duplicate of [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – m.edmondson Apr 21 '13 at 15:41
  • 1
    You know about `if`/`else` statements I presume? Are you really asking then, ["How do I check to see if an object has a property in Javascript?"](http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-a-property-in-javascript) Or you may be tripping up because of `for..in` use. See http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Crescent Fresh Apr 21 '13 at 15:41
  • [This is a nice article for checking the existence of a property.](http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/) – The Alpha Apr 21 '13 at 15:55

3 Answers3

1

Try

$.each(data.businesses, function(index, business){
    if(business.telephone){
        $('body').append( "<p>" + business.telephone + "</p>");
    }
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1
for (var i in data.businesses) {
    if(data.businesses[i].telephone)
        $('body').append( "<p>" + data.businesses[i].telephone + "</p>");
 }
Harry Bomrah
  • 1,658
  • 1
  • 11
  • 14
0

Try this:

for (var i in data.businesses) {
    if(data.businesses[i].telephone  !== null and data.businesses[i].telephone !== undefined) {
        $('body').append( "<p>" + data.businesses[i].telephone + "</p>");
    }
}
Jesse
  • 8,605
  • 7
  • 47
  • 57
  • [This is a nice article for checking the existence of a property.](http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/) – The Alpha Apr 21 '13 at 15:54