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

本文关键字:属性 数据源 何获取 获取 | 更新日期: 2023-09-27 17:57:33

我在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"}
        });

我已经在剑道网格中有了这个列表。现在,我想将网格中的预算总和放入一个新的数据源中,这样我就可以将其与剑道条形图绑定。

如何将所有属性的总和放入vm.dataTotal

亲切问候

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

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

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)

下面是另一篇SO文章,介绍如何将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");