javascript 比较2个对象数组以查找与单个问题相关的答案

vm0i2vca  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(90)

我正在构建一个测验应用程序,我有2个对象数组。我想获得另一个数组,将他们的问题的答案关联起来。
我该怎么做?

const questions = [{
  id: 1,
  text: question1
}, {
  id: 2,
  text: question2
}, {
  id: 3,
  text: question3
}]

const answers = [{
  id: 1,
  text: answer1,
  questions_id: 1
}, {
  id: 2,
  text: answer2,
  questions_id: 1
}, {
  id: 3,
  text: answer3,
  questions_id: 1
}, {
  id: 4,
  text: answer4,
  questions_id: 1
}...]

我需要得到一个数组与每个问题的答案相关联。我知道我应该使用map或filter函数,但我从来没有用两个不同的数组进行比较。谁能帮帮我?谢谢你。我试过了,但是不起作用,它返回undef数组:

let answerQuestionId = questions.map((q,a) => {
let temp = answers.find(element => element.domanda_id === q.id)

});

rryofs0p

rryofs0p1#

这就是如何将两个数组组合成一个数组,并使用Array#mapArray#find为每个答案提供相应的问题:

const questions = [ { id: 1, text: "question1" }, { id: 2, text: "question2" }, { id: 3, text: "question3" }];

const answers = [ { id: 1, text: "answer1", questions_id: 1 }, { id: 2, text: "answer2", questions_id: 1 }, { id: 3, text: "answer3", questions_id: 1 }, { id: 4, text: "answer4", questions_id: 1 }];

const result = answers.map(a => ({
  ...a,
  question: {...questions.find(q => q.id === a.questions_id)}
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
relj7zay

relj7zay2#

你可以使用过滤器的方法来得到与问题相关联的答案。

const questions = [{
  id: 1,
  text: "question1"
}, {
  id: 2,
  text: "question2"
}, {
  id: 3,
  text: "question3"
}]

const answers = [{
  id: 1,
  text: "answer1",
  questions_id: 1
}, {
  id: 2,
  text: "answer2",
  questions_id: 1
}, {
  id: 3,
  text: "answer3",
  questions_id: 1
}, {
  id: 4,
  text: "answer4",
  questions_id: 1
}]

const data = questions.map((que) => {
  return {
    ...que,
    answer: answers.filter((ans) => ans.questions_id === que.id)
  }
})

console.log("data is ================" , data);

相关问题