skip to Main Content

I’m building a quiz app and I have 2 arrays of objects. I want to obtain another array associating the answers to their question.

How can I do this?

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
}...]

I need to get an array with the answers associated to each questions. I know I should use map or filter functions, but I’ve never done it with 2 different arrays comparing one to another. Can anyone help me? thank you.
I tried this but doesn’t work, it return an array of undef:

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

});

2

Answers


  1. This is how you could combine both arrays into a single one with the corresponding question to each answer using Array#map and Array#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; }
    Login or Signup to reply.
  2. you can use filter mathod to get associated answer with the questions.

    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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search