【问题标题】:Construct new array of objects based on existing array and object基于现有数组和对象构造新的对象数组
【发布时间】: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


    【解决方案1】:

    我认为您需要遍历引号而不是答案,然后查看答案中的引号是否匹配。

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

    【讨论】:

      【解决方案2】:

      这里是最少量循环的答案。

      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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-19
        • 1970-01-01
        • 2019-09-29
        • 1970-01-01
        相关资源
        最近更新 更多