【发布时间】: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