我有这样的东西:

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

现在,为了得到这个数组的总数量,我做了这样的事情:

$scope.totalAmount = function(){
       var total = 0;
       for (var i = 0; i < $scope.traveler.length; i++) {
              total = total + $scope.traveler[i].Amount;
            }
       return total;
}

当只有一个数组时,这很容易,但我有其他具有不同属性名的数组,我想要求和。

如果我能做这样的事情,我会更快乐:

$scope.traveler.Sum({ Amount });

但我不知道怎样才能在将来重复使用它:

$scope.someArray.Sum({ someProperty });

当前回答

下面是一个使用ES6箭头函数的一行程序。

const sumPropertyValue = (items, prop) => items.reduce((a, b) => a + b[prop], 0);

// usage:
const cart_items = [ {quantity: 3}, {quantity: 4}, {quantity: 2} ];
const cart_total = sumPropertyValue(cart_items, 'quantity');

其他回答

也可以使用Array.prototype.forEach()

let totalAmount = 0;
$scope.traveler.forEach( data => totalAmount = totalAmount + data.Amount);
return totalAmount;

我真的很沮丧,在阅读所有的代码,其中张贴作为一个解决方案,因为我是一个新的是,我试图添加一个功能到一个简单的应用程序的实践。解决这个问题的简单方法是

let testArray = [5, 7, 8, 4];

function(){
sum = 0;
for(let i = 0; i < testArray.length; i++){
    sum += testArray[i];
}

//会给你数组的和

我不确定是否有人提到过这一点。但是有一个lodash函数。下面的代码段,其中value是你要求和的属性,是“value”。

_.sumBy(objects, 'value');
_.sumBy(objects, function(o) { return o.value; });

两者都可以。

您可以执行以下操作:

$scope.traveler.map(o=>o.Amount).reduce((a,c)=>a+c);

如何使用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 = [ {描述:'高级',数量:50}, {描述:'高级',数量:50}, {描述:“成人”,数量:75}, {描述:'Child',数量:35}, {描述:“婴儿”,数量:25}, ]; 函数sum(arrayData, key){ 返回arrayData.reduce((a,b) => { 返回{金额:a.金额+ b.金额} }) } console.log(总和(旅行) `