Dirty Bird Design
Dirty Bird Design

Reputation: 5533

How to determine if JSON object has property, and that if it does is the properties value is greater than 0?

I have some returned JSON from an API similar to this:

{"amount_to_collect":0,"breakdown":{"city_tax_collectable":0,"city_tax_rate":0,"city_taxable_amount":0,"combined_tax_rate":0,"county_tax_collectable":0,"county_tax_rate":0,"county_taxable_amount":0,"line_items":[{"city_amount":0,"city_tax_rate":0,"city_taxable_amount":0,"combined_tax_rate":0,"county_amount":0,"county_tax_rate":0,"county_taxable_amount":0,"id":"1","special_district_amount":0,"special_district_taxable_amount":0,"special_tax_rate":0,"state_amount":0,"state_sales_tax_rate":0,"state_taxable_amount":0,"tax_collectable":0,"taxable_amount":0}],"special_district_tax_collectable":0,"special_district_taxable_amount":0,"special_tax_rate":0,"state_tax_collectable":0,"state_tax_rate":0,"state_taxable_amount":0,"tax_collectable":0,"taxable_amount":0}}

I need to check if the "amount_to_collect" exists, and if it does check if the value is greater than 0, including any cents IE 0.01 should be greater.

I can check if it exists with:

if (data.hasOwnProperty("amount_to_collect"))

I can check if it is greater than zero with

if(data.amount_to_collect == 0) {
    alert('zero');
} else if(data.amount_to_collect > 0) {
    alert('greater')
}

but cannot figure out how to check if it exists and if it exists is the value greater than zero. In some cases, it might not be returned and I need to have a case for that.

Upvotes: 1

Views: 1366

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

tax in your code will only ever contain the boolean result of hasOwnProperty(). Given the object in your example that will only ever be true, hence you always see the 'greater' output.

To fix this you need to separate the variable containing the result of checking that the property exists from the value of the property itself. Try this:

let data = {
  "amount_to_collect": 0
  // other properties...
}

var propertyExists = data.hasOwnProperty("amount_to_collect");
if (propertyExists && data.amount_to_collect > 0) {
  console.log('greater');
} else {
  console.log('less');
}

Upvotes: 1

Related Questions