我有两组数据,其中一组的格式如下:
title: "Test Json",
showProgressBar: "top",
showQuestionNumbers: "off",
pages: [
{
questions: [
{
type: "",
name: "",
title: "",
hasOther: true,
isRequired: true,
colCount: 4,
choices: []
}
]
}
]
};
其他格式如下:
{Answers: "“18-24”, “25-50”, “50+”",
Question: "How old are you?",
QuestionNumber: "1",
isRequired: "TRUE",
type: "radiogroup"}
第二组数据是这些对象的多个,我使用 forEach
循环对其进行循环,如下所示:
data.forEach((data, i)=>{
console.log(data)
// returns above object x3
})
我想要做的是使用第一个对象,并使用第二个对象的值将值映射到 questions
数组,例如 questions[0].type
将映射到 data.type
。
我已经设法将一个对象映射到模板,这样做:
data.forEach((data, i)=>{
console.log(data)
questions[0].type = data.type
questions[0].name = data.Question
questions[0].title = data.Question
questions[0].choices = [data.Answers]
})
但这仅映射对象数据数组中的第一个对象,我想基本上根据数据数组中的对象数量创建一个新的模板对象,并创建与对象一样多的“填充问题模板”在数据数组中
任何指示和帮助都会很可爱<3
最佳答案
试试这个
data.forEach((data, i)=>{
console.log(data)
questions.push([{
type: data.type
name: data.Question
title: data.Question
choices: [data.Answers]
}])
})
用您的附加问题更新了此答案
关于javascript - 循环遍历对象数组并将每个对象映射到单个模板对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61297366/