如何按字母顺序列出选项。我正在运行代码here中的测验应用程序。我需要按字母顺序列出响应。我怎么做?
以下是发送到模板的问题列表
回复
var quiz = {
title: 'My quiz',
questions: [
{
text: "Question 1",
responses: [
{text: 'Wrong, too bad.'},
{text: 'Right!', correct: true},
]
}, {
text: "Question 2",
responses: [
{text: 'Right answer', correct: true},
{text: 'Wrong answer'},
]
}
]
};
我正在尝试使用过滤器
Vue.filter('myMapping',function(index){
mapping = ["A", "B", "C" , "D", "E"];
return mapping[index];
});
<div class="ques_block" v-for="(question, index) in quiz.questions">
<div v-show="index === questionIndex">
<h3>{{index + 1}}) {{question.text}}</h3>
<div class="option_div" v-for="(response,resp) in question.responses">
<input type="radio" v-bind:name="index" v-bind:value="response.correct" v-model="userResponses[index]"/>
<label> {{resp| myMapping}}) {{response.text}} </label>
</div>
</div>
</div>
这更像是一个javascript问题而不是vuejs问题。您可能希望在显示数组之前对其进行排序。
声明数组后,您可以运行此排序代码段。
quiz.questions.sort((a, b) => a.text.localeCompare(b.text));
quiz.questions.forEach(({ responses }) => responses.sort((a, b) => a.text.localeCompare(b.text)));
这样做是在按顺序使用键(文本)时对外部“对象”进行排序,一旦外部对象已经排序,您循环遍历对象内部的响应数组,以使用键(文本)对每个对象进行排序升序。