{
correct: "Warren Harding",
incorrect:
0: "Theodore Roosevelt",
1: "Andrew Jackson "
}
我有了这个对象,我想把它变成一个数组包含这样的对象:
[answerOptions: [{answerText: "Warren Harding", isCorrect: true}, {answerText: "Theodore Roosevelt", isCorrect: false}, {answerText: "Andrew Jackson", isCorrect: false}]
我怎么能做到这一点,因为我一直想弄清楚这个问题,但我怎么也弄不清楚。
OP文字几乎是一个有效的对象…
{
correct: "Warren Harding",
incorrect:
0: "Theodore Roosevelt",
1: "Andrew Jackson "
}
假设嵌套的incorrect
对象缺少花括号,那么直接的答案是这样的(请参阅代码片段中正确形成的输入)…
// fix the input
const question = {
correct: "Warren Harding",
incorrect: { // <- open curly
0: "Theodore Roosevelt",
1: "Andrew Jackson "
} // <- close curly
}
// take a question with the above form and produce an array
// of { answerText, isCorrect }
function optionsFromQuestion(question) {
return [
{ answerText: question.correct, isCorrect: true },
...Object.values(question.incorrect).map(answerText => {
return { answerText, isCorrect: false }
})
]
}
const answerOptions = optionsFromQuestion(question)
console.log(answerOptions)
假设你的输入对象是这样的:
data = { correct: "Warren Harding",
incorrect: {
0: "Theodore Roosevelt",
1: "Andrew Jackson "
}
}
你可以这样做:
result = { answerOptions: [
{ answerText: data.correct, isCorrect: true},
...Object.values(data.incorrect).map(x => ({ answerText: x, isCorrect: false }))
] }