[英]Count number of objects in json array
I have a json array stored in a url like 我有一个JSON数组存储在URL中
http://localhost/heart/api/restApiController/dataset.json
Json array looks like this Json数组看起来像这样
[
{
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. 我想计算此数组中的对象数,以及有多少个具有Heart_attack:'0'
值的对象。 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. 向您提到的url发出ajax请求,并在请求的成功回调中找到数组的长度。
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
使用.filter
获取Heart_attack = 0
的数组元素,然后应用.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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.