计算json数组中的对象数

时间:2016-05-22 06:00:02

标签: arrays angularjs json

我有一个json数组存储在像

这样的URL中
test/integration/default/default.yml

Json数组看起来像这样

http://localhost/heart/api/restApiController/dataset.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" } ] 值的对象数。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

向您提到的网址发出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);
}

答案 1 :(得分:0)

使用.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);