在javascript

时间:2016-07-19 09:02:27

标签: javascript c# arrays

我有一个对象数组,我想通过一次循环。这是javascript的代码。

   data.projectModelList.sum = function (prop) {
           var total = 0;
           for (var i = 0, _len = this.length; i < _len; i++) {
              total += this[i][prop];
           }
           return total;
        }

        vm.dataTotal = [data.projectModelList.sum("budget"),
                        data.projectModelList.sum("tax"),
                        data.projectModelList.sum("money"),
                        data.projectModelList.sum("balance"),
                        data.projectModelList.sum("amount"),
                        data.projectModelList.sum("current"),
                        data.projectModelList.sum("after"),
                        data.projectModelList.sum("discount")]

当我循环时,我得到预算,税金,金钱,余额,金额,当前,之后,折扣超过1.我只想循环通过,然后结果必须是每个项目显示一次而不是更多。我知道我需要在for循环中改变一些东西,但我不知道是什么。

亲切的问候

编辑:

ModelItem

  public class ProjectDashBoardModel
   {
      public decimal budget { get; set; }
      public decimal tax{ get; set; }
      public decimal money{ get; set; }
      public decimal balance{ get; set; }
      public decimal amount{ get; set; }
      public decimal current{ get; set; }
      public decimal after{ get; set; }
      public decimal discount{ get; set; }     
   }

   public class ProjectDashboard
   {
      public Guid Id { get; set; }
      public string ProjectLogo { get; set; }
      public string LastMutatedBy { get; set; }
      public DateTime LastMutatedDate { get; set; }
      public List<ProjectDashBoardModel> ProjectModelList { get; set; }


   }

1 个答案:

答案 0 :(得分:0)

您可以更改sum函数以返回一个对象,其中 all 总和为属性 - 这意味着您只需要循环数组一次。

data.projectModelList.sum = function (props) {
       var total = {};
       for (var i = 0, _len = this.length; i < _len; i++) {
         for(var j=0;j<props.length;i++){
          var prop = props[j];
          if(total[prop] === undefined){
              total[prop] = 0;
          }
          total[prop] += this[i][prop];
         }
       }
       return total;
    }

您可以使用所需的所有属性数组调用它:

var sums = data.projectModelList.sum(['budget','tax','money']);

然后你会用点或括号表示法读取总和

var budgetTotal = sums.budget;
var moneyTotal = sums['money'];