简体   繁体   中英

Check if an object has a key and it's value is not 0 Javascript

I have a scenario where I want to show data of an object based on certain conditions: Here's my Object data:

"charges": {
  "main": "28",
  "extra": "0",
  "extra_01": "806.59",
  "Others": "-230"
}

This is how I'm showing this data in my template:

<% _.each(model.get("charges"),function(item,key) { %>
      <% if(parseInt(item)) { %>
      <section>
        <span>
          <%=key %>
        </span>
        <span class="pull-right">
          $<%= model.getFormattedAmount(item) %>
          </span>
      </section>
      <% } %>
      <% }); %>

So now I've to put a check if there is bpp and not 0 , then show only bpp and Others . Else have to show extra stuff like extra and extra_01 . To check if bpp exists, I've done something like this:

var exist = _.has(model.get("charges"), 'bpp');

Can anyone please suggest what is the right way to go about it? Thank in advance!

You can just do

if(model.get("charges").bpp){
  // value exists
  // not 0
  // not false
  // not Null
  // not undefined
  // not ""
  // not NaN
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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