Reputation: 1241
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
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
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