簡體   English   中英

基於現有數組和 object 構造新的對象數組

[英]Construct new array of objects based on existing array and object

可能犯了一個愚蠢的錯誤,但我似乎無法弄清楚這一點。

基於現有的字符串數組,我想檢查它們是否作為 object 值存在於我的對象數組中。 如果為真,則將它們推入具有真值的新數組,如果為假,也將它們推入新數組,但具有假值。

到目前為止我的代碼示例:

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}創建一個 object 。
  2. 循環遍歷答案,同時檢查在第 1 點創建的 object 中的答案是否正確)。

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM