【问题标题】:Why is this turning to 2d array?为什么这转向二维数组?
【发布时间】:2018-05-10 13:37:14
【问题描述】:

我在这里有一些关于对象的模拟问题(不要介意他们胡言乱语的问题和选择)

const questions = {
  iq_test: {
    questions: [
    {
      question: 'Find the difference', 
      choices: ['a1', 'a2', 'a1', 'a3'], 
      correct: 0
    }, 
    {
      question: 'What is the next sequence', 
      choices: ['2', '5', '56', '64'],
      correct: 3
    }, 
    { question: 'What should be the next letter', 
      choices: ['c', 'z', 'e', 'f'],
      correct: 3
    }]
  },
 memory_test: {
   ...omitted
 }
}

现在我想要iq_test

let retQuestions = Object.values(questions.iq_test).map(item => {
      console.log(item);
      return item;
})

地图中的 console.log 给了我这种格式

    [ { question: 'Find the difference',
    choices: [ 'a1', 'a2', 'a1', 'a3' ],
    correct: 0 },
  { question: 'What is the next sequence',
    choices: [ '2', '5', '56', '64' ],
    correct: 3 },
  { question: 'What should be the next letter',
    choices: [ 'c', 'z', 'e', 'f' ],
    correct: 3 } ]

但是当我 console.log 应该保存返回值的 retQuestions 我得到不同的格式

console.log(retQuestions) 如下所示,它变成了二维数组

[ [ { question: 'Find the difference', choices: [Array], correct: 0 },
    { question: 'What is the next sequence',
      choices: [Array],
      correct: 3 },
    { question: 'What should be the next letter',
      choices: [Array],
      correct: 3 } ] ]

这次我想再次映射到 retQuestions 以获取每个问题,但我不能,因为格式正在改变..

【问题讨论】:

  • 因为你使用map你需要retQuestions.forEach(x=>console.log(x))
  • @appleapple OP 只是不需要console.log 的值:)
  • @AnkitAgarwal :)

标签: javascript arrays object


【解决方案1】:

Object.values 返回该对象中所有值的数组。由于questions.iq_test 本身是一个只有一个键值对的对象,因此在这种情况下您将得到一个二维数组。尝试记录一次。

对于您想要实现的目标,您应该直接在对象的值上调用 map。例如,

let retQuestions = questions.iq_test.questions.map(item => {
      console.log(item);
      return item;
});

【讨论】:

    【解决方案2】:

    Object.values() 方法返回给定对象自己的可枚举属性值的数组,其顺序与 for...in 循环提供的顺序相同(不同之处在于 for-in 循环枚举原型链)。

    因此,在您的情况下,您需要在 questions.iq_test.questions 上执行 map,并且由于您只是返回 item,因此您可以避免使用 return 关键字。

    const questions = {
      iq_test: {
        questions: [
        {
          question: 'Find the difference', 
          choices: ['a1', 'a2', 'a1', 'a3'], 
          correct: 0
        }, 
        {
          question: 'What is the next sequence', 
          choices: ['2', '5', '56', '64'],
          correct: 3
        }, 
        { question: 'What should be the next letter', 
          choices: ['c', 'z', 'e', 'f'],
          correct: 3
        }]
      },
     memory_test: {
     }
    }
    
    let retQuestions = questions.iq_test.questions.map(item => item);
    console.log(retQuestions);

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2017-04-22
      相关资源
      最近更新 更多