Search code examples
javascriptarraysarray-map

Array javascript to match answer and questions by id


I have an array form lke this

const options = [
  {
    id: 1,
    content: 'Hello'
  },
  {
    id: 2,
    content: 'Hi'
  }
]

const answers = [
  {
    id: 400,
    content: 'World',
    optionKey: 1
  },
  {
    id: 500,
    content: 'There',
    optionKey: 2
  }
]

expected output

const expecetedOutput = [
  {
    option: {
      id: 1,
      content: 'Hello'
    },
    answer: {
      id: 400,
      content: 'World'
    }
  },
  {
    option: {
      id: 2,
      content: 'Hi'
    },
    answer: {
      id: 500,
      content: 'There'
    }
  }
];

What i have tried

i have tried using map and find but the result still not as expected

const optionWithAnswer = answers.map((answer) => {
  return {
    option: options.find((option) => option.id === answer.optionKey),
    answer: answers.find((answer) => answer.optionKey === options.find((option) => option.id === answer.optionKey).id)
  }
})

result i got. the answer will always found the first index of answer array

[
  {
    option: { id: 1, content: 'Hello' },
    answer: { id: 400, content: 'World', optionKey: 1 }
  },
  {
    option: { id: 2, content: 'Hi' },
    answer: { id: 400, content: 'World', optionKey: 1 }
  }
]

what i'm supposed to do. is this something that should accomplish using reduce ?


Solution

  • options.map(opt => ({
        option: opt,
        answer: answers.find(i => i.optionKey === opt.id)
    }));