【发布时间】:2018-09-13 15:44:05
【问题描述】:
我想创建一个具有给定结构的对象:
const questions = [
{
id: '1',
instruction: 'Question1',
options: {
'a': 'SomeText1',
'b': 'SomeText2',
'c': 'SomeText3'
},
correct: ['c']
},
{
id: '2',
instruction: 'Question2',
options: {
'a': 'SomeText1',
'b': 'SomeText2',
'c': 'SomeText3',
'd': 'SomeText4'
},
correct: ['a']
},
{
id: '3',
instruction: 'Question3,
options: {
'a': 'SomeText1',
'b': 'SomeText2'
},
correct: ['b']
}
]
我有一个数组,其中包含填充此对象并使用 .map() 创建它的必要信息。
const questions =
[ 'Question1',
'Question2',
'Question3'
]
const answers =
[
'Answer1',
'Answer2',
'Answer3'
]
const options = [
[ 'Option1', 'Option2', 'Option3' ],
[ 'Option4', 'Option5', 'Option6' ],
[ 'Option7', 'Option8', 'Option9' ]
]
function toJson()
const alphabet = ['a', 'b', 'c', 'd', 'e'];
const json = questions.map((question, index) => (
{
id: index + 1,
instruction: question,
options: Object.assign({}, options[index]),
correct: answers[index]
}
))
}
我只有options 键有问题。如您所见,我希望将字母作为键,具体取决于问题的答案数量。
当我使用Object.assign() 时,此函数将数字作为键,我不知道如何将它们替换为alphabet 数组中的字母。
编辑:
因此,options 键在所需对象中的解决方案是:
options: Object.assign(
{},
...options[index].map((a, i) => ({ [alphabet[i]]: a }))
),
现在我可以创建一个带有指定答案的连续字母的对象。
【问题讨论】:
-
你能告诉我们
options变量是什么吗? -
添加了
options变量。内容当然无关紧要。
标签: javascript arrays function object