如何获取数据源中的属性总和?

时间:2016-07-18 14:29:37

标签: javascript c# angularjs

我在C#中得到了一个模型项目:

public class ProjectDashBoardModel
   {      
      public decimal Budget { get; set; }
      public decimal Amount { get; set; }
      public decimal Balance { get; set; }
      public decimal Tax { get; set; }
      public decimal Money1 { get; set; }
      public decimal Money2 { get; set; }
      public decimal Balance_2 { get; set; }
      public decimal Balance_3 { 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; }


   }

这是我的数据源代码:

   vm.dataTotal = data.projectModelList;   

我希望所有属性都是它的总和

我已经尝试过这样的事情,但没有成功

 vm.dataTotal = data.projectModelList(function () {
          {field: "budget", aggregate: "sum"}
        });

我已经在kendo网格中有这个列表。现在我希望网格中的预算总和成为一个新的数据源,因此我可以将其与kendo条形图绑定。

如何将所有属性总和纳入vm.dataTotal?

亲切的问候

2 个答案:

答案 0 :(得分:0)

Here is another SO post了解如何将Sum函数添加到数组中。您可以使用它:

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");

答案 1 :(得分:0)

如果您要在JS中获得数组的总和,最好使用Array.prototype.reduce: 您可以在任何地方使用结果(total变量),例如&#39; vm.set(&#39; total&#39;,total)will bind it to your observable vm`object。

&#13;
&#13;
var data = { projectModelList: [ { "budget": 245, "amount": 500 , "balance": 2323, "tax": 234, "money1": 23, "money2": 6345, "balance_2": 123123, "balance_3": 3423}, { "budget": 245, "amount": 500 , "balance": 2323, "tax": 234, "money1": 23, "money2": 6345, "balance_2": 123123, "balance_3": 3423}, { "budget": 245, "amount": 500 , "balance": 2323, "tax": 234, "money1": 23, "money2": 6345, "balance_2": 123123, "balance_3": 3423}, { "budget": 245, "amount": 500 , "balance": 2323, "tax": 234, "money1": 23, "money2": 6345, "balance_2": 123123, "balance_3": 3423}, ] };

var total = data.projectModelList.reduce(function(t, d) {
	Object.keys(t).forEach(function(k) {
		t[k] += (d[k] || 0);
	});
	return t;
})
console.log(total)
&#13;
&#13;
&#13;