目前,Calculated Model Sample app仅计算每个类型的记录计数。我还想计算每个类型的评分总和。
为了简要说明应用的数据模型,每条记录都有三个字段:名称 (str)、类型 (str) 和评级 (num)。
我已将求和 字段添加到聚合计算模型中,但不清楚我到底需要在代码中更改什么CalculatedModels 脚本。
这里是计算每个类型的计数的代码块。我添加了 records.Sum =
来指示应如何以及在何处记录 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;
}
最佳答案
这应该可以做到。抱歉暂时没有时间解释。
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;
}
关于javascript - 计算模型总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47518599/