Better way to sum a property value in an array

后端 未结 16 1770
遥遥无期
遥遥无期 2020-11-22 02:41

I have something like this:

$scope.traveler = [
            {  description: \'Senior\', Amount: 50},
            {  description: \'Senior\', Amount: 50},
             


        
16条回答
  •  礼貌的吻别
    2020-11-22 03:26

    How to sum array of object using Javascript

    const traveler = [
      {  description: 'Senior', Amount: 50},
      {  description: 'Senior', Amount: 50},
      {  description: 'Adult', Amount: 75},
      {  description: 'Child', Amount: 35},
      {  description: 'Infant', Amount: 25 }
    ];
    

    const traveler = [
        {  description: 'Senior', Amount: 50},
        {  description: 'Senior', Amount: 50},
        {  description: 'Adult', Amount: 75},
        {  description: 'Child', Amount: 35},
        {  description: 'Infant', Amount: 25 },
    ];
    function sum(arrayData, key){
       return arrayData.reduce((a,b) => {
      return {Amount : a.Amount + b.Amount}
    })
    }
    console.log(sum(traveler))
    `

提交回复
热议问题