【发布时间】:2021-05-21 18:39:08
【问题描述】:
可能犯了一个愚蠢的错误,但我似乎无法弄清楚这一点。
基于现有的字符串数组,我想检查它们是否作为对象值存在于我的对象数组中。如果为真,则将它们推送到具有真值的新数组中,如果为假,也将它们推入新数组中,但具有假值。
到目前为止我的代码示例:
const answers = [12, 3, 16]
const quotes = [
{ id: 12, author: 'A'},
{ id: 4, author: 'B'},
{ id: 16, author: 'C'},
]
let checkedQuotes = [];
answers.forEach((answer) => {
quotes.find((quote) => (quote.id === answer
&& checkedQuotes.push({
id: quote.id,
author: quote.author,
correct: true,
})
));
});
returns => [
{id:12, author: 'A', correct: true},
{id:16, author: 'C', correct: true}
]
这会将对象推送到我的新数组中,并且一切正常!问题是当我想添加错误的。我正在尝试这样做:
answers.forEach((answer) => {
quotes.find((quote) => (quote.id === answer
? checkedQuotes.push({
id: quote.id,
author: quote.author,
correct: true,
})
: checkedQuotes.push({
id: quote.id,
author: quote.author,
correct: false,
})
));
});
returns => [
{id:12, author: 'A', correct: true},
{id:12, author: 'A', correct: false},
{id:12, author: 'A', correct: false}
]
// would expect it to be:
[
{id:12, author: 'A', correct: true},
{id:4, author: 'B', correct: false},
{id:16, author: 'C', correct: true}
]
我在这里错过了什么?
【问题讨论】:
标签: javascript arrays object