1

I'm looking to get count of active products according to this JSON data.

$(document).ready (function () {


var JSONdata = {
    "products":[
          {
            "id_product":"261",
            "status":"Active",
            "price":"50.00"
          },
          {
            "id_product":"267",
            "status":"Active",
            "price":"100.00"
          },
          {
            "id_product":"280",
            "status":"Inactive",
            "price":"600.00"
          }

    ]


};     

 alert("Active products : " + JSON.stringify(JSONdata.length));


  //Excepted result
  //Active products : 2 

});

I made a JSfiddle, I couldn't figure it out how to get count of active products.

http://jsfiddle.net/ot6emj0n/2/

This JSON data contains 3 products, 2 actives and 1 inactive.

Excepted result what Im looking is "Active products: 2"

Ivan
  • 1,221
  • 2
  • 21
  • 43

2 Answers2

3

Use filter() , filter the array based on your condition using filter() then get it's length.

var JSONdata = {
  "products": [{
    "id_product": "261",
    "status": "Active",
    "price": "50.00"
  }, {
    "id_product": "267",
    "status": "Active",
    "price": "100.00"
  }, {
    "id_product": "280",
    "status": "Inactive",
    "price": "600.00"
  }]
};


alert("Active products : " + JSONdata.products.filter(function(v) {
  return v.status == "Active";
}).length);

Note: JSONdata is an object it doesn't have length property . You need to use JSONdata.products for the array.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • This answer works very well, I wonder why JSONdata.products gave me "undefined" however I added it [ 1 ] at end of JSONdata.products it gave me a list, anyway thank you. – Ivan Oct 09 '15 at 17:51
1

I've made and updated JSfiddle for you which will return the active products: http://jsfiddle.net/7es6vuc1/3/

$(document).ready (function () {


    var JSONdata = {
        "products":[
            {
                "id_product":"261",
                "status":"Active",
                "price":"50.00"
            },
            {
                "id_product":"267",
                "status":"Active",
                "price":"100.00"
            },
            {
                "id_product":"280",
                "status":"Inactive",
                "price":"600.00"
            }
        ]    
    };

    var totalProducts = JSONdata.products.length,
        activeProducts = 0,
        inactiveProducts = 0;

    $.each(JSONdata.products, function (key, val) {
        if (val.status === 'Active') {
            activeProducts++;
        }
    });

    inactiveProducts = totalProducts - activeProducts;

    $('#total').text(totalProducts);
    $('#active').text(activeProducts);
    $('#inactive').text(inactiveProducts);

});

Basically, you need to loop over the objects and look for the status property and then count the active ones.