[英]Count the number of occurrences and add it to grouped objects in a JSON array
[英]Count number of objects in json array
我有一個JSON數組存儲在URL中
http://localhost/heart/api/restApiController/dataset.json
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"
}
]
我想計算此數組中的對象數,以及有多少個具有Heart_attack:'0'
值的對象。 我怎樣才能做到這一點?
向您提到的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);
}
使用.filter
獲取Heart_attack = 0
的數組元素,然后應用.length
var arr; // Represent your array
arr.filter(function (item) {
return item.Heart_attack == 0;
}).length;
工作示例:
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.