1

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 ?

2
  • so I guess you don't want the optionKey property in the expected output ..right? Commented Jul 18, 2021 at 11:04
  • no . it can be there. i just want the result to be match by id of options to optionkey of answer Commented Jul 18, 2021 at 11:08

1 Answer 1

4
options.map(opt => ({
    option: opt,
    answer: answers.find(i => i.optionKey === opt.id)
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.