我正在从API中提取数据,该API使我得到了一个项目对象,每个项目都包含一个名为allResluts.forEach(System.out::println);
的字符串和一个名为new DataColumn("ColumnName", "ColumnType","Expression to Set AllowNull")
的数组。
我试图在每个项目中合并这些值,所以当我执行correct_answer
时,它将循环遍历合并在一起的答案。我也想将这些答案的顺序随机化。
对象外观示例:
incorrect_answers
答案 0 :(得分:0)
let merged = [item.correct_answer, ...item.incorrect_answers]
,还是我缺少什么?
答案 1 :(得分:0)
var res = [
{
"question": "Where was the Games of the XXII Olympiad held?",
"correct_answer": "Moscow",
"incorrect_answers": [
"Barcelona",
"Tokyo",
"Los Angeles"
]
},
{
"question": "What is the first weapon you acquire in Half-Life?",
"correct_answer": "A crowbar",
"incorrect_answers": [
"A pistol",
"The H.E.V suit",
"Your fists"
]
},
]
var answers = res.map(i => [i.correct_answer, ...i.incorrect_answers])
console.log(answers[0])
console.log(answers[1])
答案 2 :(得分:0)
您可以将incorrect_answers
的1️⃣spread放入correct_answer
的新数组中,然后2️⃣将结果作为新属性附加到原始数据上。此外,3️⃣您可以shuffle在答案时:
const newData = data.map(x => {
const answers = [x.correct_answer, ...x.incorrect_answers] /*1️⃣*/
x.answers /*2️⃣*/ = shuffle(answers) /*3️⃣*/
return x
})
此新数组可以用作模板中的computed property(例如,名为questions
):
<fieldset v-for="q in questions" :key="q.question">
const rawData = {
"results": [
{
"question": "Where was the Games of the XXII Olympiad held?",
"correct_answer": "Moscow",
"incorrect_answers": [
"Barcelona",
"Tokyo",
"Los Angeles"
]
},
{
"question": "What is the first weapon you acquire in Half-Life?",
"correct_answer": "A crowbar",
"incorrect_answers": [
"A pistol",
"The H.E.V suit",
"Your fists"
]
},
]
}
new Vue({
el: '#app',
data() {
return {
rawData: rawData.results
}
},
computed: {
questions() {
return this.rawData.map(x => {
const answers = [x.correct_answer, ...x.incorrect_answers]
x.answers = shuffle(answers)
this.$set(x, 'answer', null) // create reactive answer prop
return x
})
}
}
})
// https://stackoverflow.com/a/2450976/6277151
function shuffle(array) {
let currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
<script src="https://unpkg.com/vue@2.6.10"></script>
<div id="app">
<form action="#">
<fieldset v-for="(q,i) in questions" :key="q.question">
<h2>{{q.question}} {{q.answer}}</h2>
<div v-for="a in q.answers" :key="a">
<label>
<input type="radio" :name="i" :value="a" @change="q.answer = a">
<span>{{a}}</span>
</label>
</div>
</fieldset>
</form>
</div>