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
5 Answers
Reset to default 3Use 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条)