questions.jso n和 answers.json 有两个文件。目的是制作一个摘要页面,根据questionID
和answerValues
以及 answers.json中的answerValues
和values.id
显示所选答案及其问题即可。有结果将结果输入一个变量吗?
演示:https://codesandbox.io/s/pj9z6n3r20
我在React ES6中的不良做法
const results = answers.map(answer => {
console.log(answer)
return questions.find(question => {
console.log(question);
return question.questionID == answer.questionID
});
});
console.log(results)
Questions.JSON
const questions = [
{
questionID: 1,
title: "Your gender ?",
values: [{ id: "1", value: "Male" }, { id: "2", value: "Female" }]
},
{
questionID: 2,
title: "Choose your age ?",
values: []
},
{
questionID: 3,
title: "Do you look at a screen within one hour of going to sleep ?",
values: [{ id: "1", value: "Yes" }, { id: "2", value: "No" }]
},
{
questionID: 4,
title: "What do you do most time on mobile",
values: [
{ id: "1", value: "Social media" },
{ id: "2", value: "Play game" },
{ id: "3", value: "Chat" },
{ id: "4", value: "Surf on internet" },
{ id: "5", value: "Call" }
]
},
{
questionID: 5,
title: "On average, how many hours of sleep do you get every night ?",
values: [
{ id: "1", value: "4-6" },
{ id: "2", value: "7-9" },
{ id: "3", value: "10-11" }
]
},
{
questionID: 6,
title: "Any additional comments or information we should know ?",
values: []
}
];
Answers.JSON
const answers = [
{
questionID: "1",
answerValues: "1"
},
{
questionID: "2",
answerValues: "12"
},
{
questionID: "3",
answerValues: "1"
},
{
questionID: "4",
answerValues: ["2", "4"]
},
{
questionID: "5",
answerValues: "2"
},
{
questionID: "6",
answerValues: "323123123123"
}
];
答案 0 :(得分:1)
您忘记返回questions.find
的结果:
const results = answers.map(answer => {
return questions.find(question => {
return question.questionID == answer.questionID
})
})
如果你需要某种 merge ,我的方法就是这样:
const results1 = answers.map((answer) => {
const question = questions.find(question => question.questionID == answer.questionID)
return { question: question.title, answer: answer.answerValues }
})
然后你会得到一系列具有以下结构的相关Q& A对象:
{
"question": "Choose your age ?",
"answer": "12"
}
答案 1 :(得分:0)
https://codesandbox.io/s/82okp2j630
const results = answers.map(answer => {
// first find the associated question
let question = questions.find((q) => q.questionID == answer.questionID);
// since your data structure is either array or string
let answerValues = (answer.answerValues instanceof Array)? answer.answerValues : [answer.answerValues];
answerValues = answerValues.map((value) => {
// grab the object associated with the current answer
const questionValue = question.values.find((q) => (q.id === value));
// if there is no associated answer just return the value
return (questionValue)? questionValue.value : value;
});
// return the expected structure used in the React component
return {
title: question.title,
// separate each answer by ,
value: answerValues.join(", ")
}
});
然后在你的React组件中
<h3>{result.title}</h3> Answer: {result.value}
// Results:
/// What do you do most time on mobile
/// Answer: Play game, Surf on internet