jQuery $.post data assign to vaiable if more than 0

I'm calling data from MySQL using jquery $.post

var fruitInfo ='';
$.post('test.php',
        {
          b:'fruits'
        },
        function(data){
          //console.log(data[0]['val1']);
          for(var i=0; i<data.length; ++i) {
              //if data[0]['appleStocks'] is not 0 -> `fruitInfo` += '<p>appleStocks</p>'
              //if data[0]['grapesStocks'] is not 0 -> `fruitInfo` += '<p>grapesStocks</p>'
              //check if custom data is not 0 add to `fruitInfo`
          }
        });

My question is, I need to add certain field values received in to fruitInfo if the returned value is not 0. Should these custom fields be stored in an array to be checked? How should I do this?

ex: The php returns the

storeNumber = 123, 
grapeTypes = a,b,
AppleTypes = b,
LycheeTypes = a,b,
grapeStocks = 91,
appleStocks = 0,
lycheeStocks = 25,

By using (data[0]['grapeStocks'], data[0]['appleStocks'] and data[0]['lycheeStocks'] I want to be able to update var fruitInfo as below

fruitInfo = '<p>grapeStocks = 91, lycheeStocks = 25</p>';

Answers 1

  • Change your for loop inside the callback handler to

         var fruits = {"appleStocks" : 0, "grapesStocks" : 0};
         for(var i=0; i<data.length; ++i) {
    
              if (data[0]['appleStocks'] > 0 ){ fruits[appleStocks] += data[0]['appleStocks'] }
              else if (data[0]['grapesStocks'] > 0 ){ fruits[grapesStocks] += data[0]['grapesStocks'] }
         }
         var fruitInfo = "<p>" + Object.keys(fruits).map(function(value){return key + "=" + fruits[key];}).join(" , ") + "</p>" ;
    

Related Articles