javascript - calculate the total value in variable from from a json array - Stack Overflow

I have a json response that returns an array. From the array I want to calculate the total of a variabl

I have a json response that returns an array. From the array I want to calculate the total of a variable in the json array. here is a snippet

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

    returns

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

how to calculate the total age in the array to get 60 is a challenge

I have a json response that returns an array. From the array I want to calculate the total of a variable in the json array. here is a snippet

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

    returns

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

how to calculate the total age in the array to get 60 is a challenge

Share Improve this question asked Nov 23, 2018 at 17:18 user10445503user10445503 1651 silver badge13 bronze badges 1
  • 1 Please share the code which you have tried. – Hassan Imam Commented Nov 23, 2018 at 17:21
Add a ment  | 

5 Answers 5

Reset to default 3

Use a fold/reduce

res.data.data.reduce(function (total, person) {
  return total + person.age;
}, 0);
   $scope.data =   [{
        "name":"John",
        "age":30
        },
    {
        "name":"Doe",
        "age":30
        }]

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

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

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

Try a for..of loop:

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 iterates over every element of an array (or any other iterable). Then you can easily sum up the total (here stored in the sum variable).

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)
    
    

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744753396a4591734.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信