简体   繁体   English

如何判断 JSON 对象是否有属性,如果有属性值是否大于 0?

[英]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:我有一些从类似于此的 API 返回的 JSON:

{"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.我需要检查“amount_to_collect”是否存在,如果它确实检查值是否大于 0,包括任何美分 IE 0.01 应该更大。

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.在某些情况下,它可能不会被退回,我需要为此提供一个案例。

tax in your code will only ever contain the boolean result of hasOwnProperty() .您的代码中的tax将只包含hasOwnProperty()的布尔结果。 Given the object in your example that will only ever be true , hence you always see the 'greater' output.鉴于您的示例中的对象永远为true ,因此您总是会看到“更大”的输出。

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'); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM