gpt4 book ai didi

javascript - 在 ES6 中如何根据另一个对象的详细信息从一个对象获取对象详细信息

转载 作者:行者123 更新时间:2023-11-30 20:38:33 25 4
gpt4 key购买 nike

questions.json 和answers.json 两个文件。目的是制作一个摘要页面,根据 questionIDanswerValues 以及 answerValuesvalues 显示所选答案及其问题.idanswers.json 中。是否可以选择将结果放入一个变量?

演示: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)

问题.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"
}
];

最佳答案

您忘记返回 questions.find 的结果:

const results = answers.map(answer => {
return questions.find(question => {
return question.questionID == answer.questionID
})
})

如果您需要在两者之间进行某种合并,我的方法是这样的:

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"
}

关于javascript - 在 ES6 中如何根据另一个对象的详细信息从一个对象获取对象详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com