基于现有数组和对象构造新的对象数组



可能犯了一个愚蠢的错误,但我似乎不明白这一点。

基于现有的字符串数组,我想检查它们是否作为对象值存在于我的对象数组中。如果为true,则使用true值将它们推入新数组;如果为false,则也使用false值将它们放入新数组。

到目前为止我的代码示例:

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

我在这里错过了什么?

我认为你需要循环使用引号而不是答案,然后看看答案中是否有匹配的引号值。

const answers = [12, 3, 16];
const quotes = [
{ id: 12, author: 'A' }, 
{ id: 4, author: 'B' }, 
{ id: 16, author: 'C' },  
];
const res = quotes.map(
(quote) => ({ ...quote, correct: answers.includes(quote.id) })
);
console.log(res);

这里有一个关于最少循环的答案。

  1. 使用reduce从答案数组-{'value': true}中创建一个对象
  2. 循环浏览答案,同时检查在第1(点中创建的对象中的答案是否正确

const answers = [12, 3, 16]
const quotes = [
{ id: 12, author: 'A'}, 
{ id: 4, author: 'B'}, 
{ id: 16, author: 'C'},  
]
const answersObj = answers.reduce(function(obj, answer) {
obj[answer] = true;
return obj;
}, {});
for (quote of quotes) {
quote['correct'] = answersObj[quote.id] || false;
}
console.log(quotes)

最新更新