从json数组计算变量的总值

时间:2018-11-23 17:18:15

标签: javascript angularjs

我有一个返回数组的json响应。我想从数组中计算json数组中变量的总数。这是一个片段

    $rootScope.getData = function () {
                $http({ 
                method: 'GET',
    ....
    console.log(JSON.stringify(res.data.data));

    returns

    [{
    "name":"John",
    "age":30
    }
{
    "name":"Doe",
    "age":30
    }]

如何计算数组中的总年龄以获取60岁是一个挑战

5 个答案:

答案 0 :(得分:3)

使用折叠/缩小

res.data.data.reduce(function (total, person) {
  return total + person.age;
}, 0);

答案 1 :(得分:2)

   $scope.data =   [{
        "name":"John",
        "age":30
        },
    {
        "name":"Doe",
        "age":30
        }]

  $scope.sum = 0;
angular.forEach($scope.data, function(value, key){
  $scope.sum += value.age
})

朋克:http://plnkr.co/edit/tpnsgeAQIdXP4aK8ekEq?p=preview

答案 2 :(得分:2)

let sum = 0;
res.data.data.forEach((element) => {
    sum += element.age;
});
// done!

答案 3 :(得分:1)

尝试for..of循环:

let arr = [{
    "name": "John",
    "age": 30
  },
  {
    "name": "Doe",
    "age": 30
  }
];

let sum = 0;


for (let el of arr) {
  sum += el.age;
}

console.log(sum);

for..of遍历数组的每个元素(或任何其他可迭代的元素)。然后,您可以轻松地将总数求和(存储在sum变量中)。

答案 4 :(得分:0)

var data = [{
    "name":"John",
    "age":30
    },
    {
    "name":"Doe",
    "age":30
    },
    {
    "name":"Doe",
    "age":10
    }
    ]
    
    
    var totalAge = data.map((person)=> person.age)// get the age values
                        .reduce((sum, current)=> sum+ current) // sum the age values
    
    console.log(totalAge)