Javascript 对嵌套数组值执行数学运算并显示在表中
我用Angular显示了一项调查的结果,正在努力处理数据结构以及如何对表的每一列执行数学运算 数据库中将收集对同一调查的大量回复,下面的代码用于以表格形式向调查管理员显示所有回复的摘要 调查中的每个问题都有三个答案:Javascript 对嵌套数组值执行数学运算并显示在表中,javascript,angular,Javascript,Angular,我用Angular显示了一项调查的结果,正在努力处理数据结构以及如何对表的每一列执行数学运算 数据库中将收集对同一调查的大量回复,下面的代码用于以表格形式向调查管理员显示所有回复的摘要 调查中的每个问题都有三个答案: 课程评分(1-10:数量) 讲师等级(1-10:数量) 注释(字符串) 下面是这个对象数组的结构示例 [ <- Whole survey response [ <- Question 1 { question: "Introduction
[ <- Whole survey response
[ <- Question 1
{
question: "Introduction to Angular 4"
},
{
answer : 7
},
{
answer : 6
},
{
answer : 'Good lesson!'
}
],
[ <- Question 2
{
question: "Structure of an Angular 4 Application"
},
{
answer : 5
},
{
answer : 2
},
{
answer : 'Instructor went too quickly!'
}
]
]
[我不会尝试使用该模型以不同格式显示。而是在填充初始模型后,创建与其他子视图匹配的新模型
假设表1按问题编号分组,在此之后执行以下操作。设置结果以创建按问题分组的答案列表:
this.resultsGroupedByQuestions: { title: string, answers: [] } = [];
for (let res of this.results) {
for (let i = 0, il = res.length; i < il; i++) {
// if you know the number of questions then simplify this
let question = this.resultsGroupedByQuestions[i];
if (!question) {
this.resultsGroupedByQuestions[i] = question = {
title: '', answers: []
};
}
if (res[i].question) question.title = res[i].question;
if (res[i].answer) queue.answer = res[i].answer;
}
}
在您的最底层,只需执行以下操作:
<tr>
<td>Averages:</td>
<td>{{means[0] | percent:'1-1'}}</td>
<td>{{means[1] | percent:'1-1'}}</td>
<td></td>
</tr>
平均数:
{{表示[0]|百分比:'1-1'}
{{表示[1]|百分比:'1-1'}
请提供您的plnkr或JSFIDLE。@swand codepen此处:干杯。实际上我发现问题.title
与答案在同一数组中,因此{{question.title}无法访问
我如何将其向上移动一级,以便在循环之外访问?多么奇怪的结构。无论如何,我更新了我的答案。这样构造我的数据会更好吗:。我有这样做的自由。什么使answer属性成为单独的对象,只要有一个字符串数组,除非您需要更多属性?
<ng-container *ngFor="let question of resultsGroupedByQuestions; let qIndex = index">
<strong>{{qIndex}}: {{question.title}}</strong>
<ul>
<li *ngFor="let answer of question.answers">
{{answer}}
</li>
</ul>
<ng-container>
// I'm assuming you'll know what questions have numeric results
const numericQuestionIndexes = [0,1]
this.means = numericQuestionIndexes.map(index => {
this.results.reduce((p, c) => p + (c[index].answer || 0), 0) / this.results.length;
});
<tr>
<td>Averages:</td>
<td>{{means[0] | percent:'1-1'}}</td>
<td>{{means[1] | percent:'1-1'}}</td>
<td></td>
</tr>