Question:
I am using the amazon product api, my requests return xml in which encode to json.
Some items in my feed to not have a price, therefore I get the following error
1 2 |
TypeError: this.ItemAttributes.ListPrice is undefined |
However I can retrieve a sale price. So I want to basically see if
this.ItemAttributes.ListPrice is undefined if so then look for this…
this.Offers.OfferListing.Price.FormattedPrice
How can I do this in jQuery?
I tried this..
1 2 3 4 5 6 |
if (this.ItemAttributes.ListPrice != null){ var price = this.ItemAttributes.ListPrice; }else{ var price = this.Offers.OfferListing.Price.FormattedPrice } |
Answer:
Nearly. You want to be checking for undefined
, not null
.
One way to do it may be :
1 2 3 4 5 6 7 8 |
var price; if (this.ItemAttributes.ListPrice !== undefined) { price = this.ItemAttributes.ListPrice; } else { price = this.Offers.OfferListing.Price.FormattedPrice; } |
If you want to cover for all falsy values (null, undefined, zero…) you may just turn the first line into :
1 2 3 |
if (this.ItemAttributes.ListPrice) { ... |
You may write it more succintly using || or ? operators, but be sure to keep it readable.