简体   繁体   中英

How to iterate through an array of objects and add up the properties

Below is a sample array of objects :

[{Name : Deji, Age: 12}, {Name : Sonia, Age 13}, {Name : Fabio, Age: 21}]

How do I iterate through the arrays in such a way as to add up the ages of the people in the array.

Is there a function that can add up the ages of the player?

Use Array#forEach and Array#reduce to iterate over array items and add the age of each player to your variable.

forEach

 const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}]; let age = 0; players.forEach(player => age += player.Age); console.log(age); 

reduce

 const players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age: 13}, {Name : 'Fabio', Age: 21}]; const age = players.reduce((sum, player) => sum + player.Age, 0); console.log(age); 

 var players = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age : 13}, {Name : 'Fabio', Age: 21}]; var age = 0; players.forEach(function(el){ age+=el.Age; }) console.log(age) 

Loop through each object using forEach , get the element and access Age property, and add it.

First of all your JSON is not a valid one, it should be,

[ { "Name": "Deji", "Age": 12 }, { "Name": "Sonia", "Age": 13 }, { "Name": "Fabio", "Age": 21 } ]

With angularjs you can juse use array.reduce function to calculate the total.

DEMO

  angular.module('MyModule', []) .controller( 'MyController', function($scope){ $scope.data = [ { "Name": "Deji", "Age": 12 }, { "Name": "Sonia", "Age": 13 }, { "Name": "Fabio", "Age": 21 } ]; $scope.sum = function(items, prop){ return items.reduce( function(a, b){ return a + b[prop]; }, 0); }; $scope.totalAges = $scope.sum($scope.data, 'Age'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='MyModule' ng-controller='MyController'> <p>totalAges = {{totalAges}}</p> </div> 

try this

var a = [{Name : 'Deji', Age: 12}, {Name : 'Sonia', Age : 13}, {Name : 'Fabio', Age: 21}];

var sum = 0;
for(var i of a){

sum += i.Age;

}

console.log(sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM