计算模型总和

时间:2017-11-27 19:41:17

标签: javascript google-app-maker

目前,Calculated Model Sample app仅计算每个类型的记录的计数。我想计算每个类型的评级的总和

要简要说明应用的数据模型,每条记录有三个字段:名称(str),类型(str)和评级(num)。< / p>

我已将总和 字段添加到聚合计算模型中,但目前尚不清楚我需要在代码中更改的内容 CalculatedModels 脚本。

以下是计算每个类型计数的代码块。我已添加records.Sum =以指示应记录总和的方式和位置。但是,由于现有for循环增加1(计算计数),我是否需要另一个for循环,该循环将增加每个记录的评级的值(因为总和将是每个类型评分的总和?或者我可以只使用现有的for循环,正如我通过插入指示records.Sum =我在哪里?

/**
 * Gathers statistics of Data records distribution by Type field values.
 * Used by the calculated datasource AggregationByType.
 * @return {Array<Aggregation>} array of records with the stats by Type.
 */  

function getStatisticsByType_() {
      var allRecords = app.models.Data.newQuery().run();
      var stats = {};
      for (var i = 0; i < allRecords.length; i++) {
        var recordType = allRecords[i].Type;
        if (!stats[recordType]) {
          stats[recordType] = 0;
        }
        stats[recordType]++;
      }

  var records = [];
  var properties = Object.getOwnPropertyNames(stats);
  for (var j = 0; j < properties.length; j++) {
    var record = app.models.Aggregation.newRecord();
    record.Name = properties[j];
    record.Count = stats[properties[j]];
    record.Sum = 
    records.push(record);
  }
  records.sort(sortDataByName_);
  return records;
}

1 个答案:

答案 0 :(得分:0)

这应该这样做。抱歉,目前没有时间解释。

function getStatisticsByType_() {
  var allRecords = app.models.Data.newQuery().run();
  var stats = {};
  var data = [];
  for (var i = 0; i < allRecords.length; i++) {
    var recordType = allRecords[i].Type;
    var num = allRecords[i].Rating;
    if (!stats[recordType]) {
      stats[recordType] = {'Count': 0, 'Sum': 0};
    }
    stats[recordType].Count++;
    stats[recordType].Sum += num;
  }

  var records = [];
  var properties = Object.getOwnPropertyNames(stats);
  console.log(stats);
  for (var j = 0; j < properties.length; j++) {
    var record = app.models.Aggregation.newRecord();
    record.Name = properties[j];
    record.Count = stats[properties[j]].Count;
    record.Sum = stats[properties[j]].Sum;
    records.push(record);
  }
  records.sort(sortDataByName_);
  return records;
}