I have a json array stored in a url like
http://localhost/heart/api/restApiController/dataset.json
Json array looks like this
[
{
Weight: "3",
Smoking: "1",
Exercising: "0",
Food_habits: "0",
Parents_HA: "1",
Alcohol: "2",
Occupation: "1",
Working_hours: "4",
Heart_Attack: "0"
}, {
Weight: "4",
Smoking: "0",
Exercising: "1",
Food_habits: "0",
Parents_HA: "1",
Alcohol: "1",
Occupation: "1",
Working_hours: "2",
Heart_Attack: "0"
}, {
Weight: "2",
Smoking: "1",
Exercising: "1",
Food_habits: "0",
Parents_HA: "1",
Alcohol: "2",
Occupation: "1",
Working_hours: "4",
Heart_Attack: "0"
}
]
I want to count the number of objects in this array and how many objects are there which has Heart_attack:'0'
value. How can I do this?
Make a ajax request to the url you mentioned and find the length of the array in the success callback of the request.
function callback (data) {
if (data) {
var heartAttackCount = 0;
console.log("Data Length: " + data.length);
data.forEach(function (object) {
if (object.hasOwnProperty('Heart_Attack') && object['Heart_Attack'] === "0") {
++heartAttackCount;
}
});
console.log("Heart Attack Count: " + heartAttackCount);
}
Use .filter
to get the array elements with Heart_attack = 0
and then apply .length
var arr; // Represent your array
arr.filter(function (item) {
return item.Heart_attack == 0;
}).length;
Working example:
var arr = [ { Weight: "3", Smoking: "1", Exercising: "0", Food_habits: "0", Parents_HA: "1", Alcohol: "2", Occupation: "1", Working_hours: "4", Heart_Attack: "0" }, { Weight: "4", Smoking: "0", Exercising: "1", Food_habits: "0", Parents_HA: "1", Alcohol: "1", Occupation: "1", Working_hours: "2", Heart_Attack: "0" }, { Weight: "2", Smoking: "1", Exercising: "1", Food_habits: "0", Parents_HA: "1", Alcohol: "2", Occupation: "1", Working_hours: "4", Heart_Attack: "0" } ]; var len = arr.filter(function (item) { return item.Heart_Attack == 0; }).length; document.write(len);
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.