【问题标题】:Array javascript to match answer and questions by id数组 javascript 按 id 匹配答案和问题
【发布时间】:2021-07-18 10:58:34
【问题描述】:

我有一个像这样的数组形式

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

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

预期输出

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

我尝试过的

我尝试过使用 map 和 find,但结果仍然不如预期

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

我得到的结果。答案总是会找到答案数组的第一个索引

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

我应该做什么。这是应该使用 reduce 完成的事情吗?

【问题讨论】:

  • 所以我猜你不希望预期输出中的 optionKey 属性..对吗?
  • 没有。它可以在那里。我只是希望结果通过选项的 id 与答案的选项键匹配

标签: javascript arrays array-map


【解决方案1】:
options.map(opt => ({
    option: opt,
    answer: answers.find(i => i.optionKey === opt.id)
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多