Ivan
Ivan

Reputation: 1241

How to pick and compare value with JSON data?

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"

Upvotes: 1

Views: 98

Answers (2)

Captain Nova
Captain Nova

Reputation: 31

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.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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.

Upvotes: 3

Related Questions