首页 > 解决方案 > 在 React 中转换对象的对象

问题描述

我对 JS 和 React 还很陌生,我遇到了以下问题(也许很简单,但我不知道如何解决这个问题)。

这是我拥有的对象:

{
  React: {
    title: 'React',
    questions: [
      {
        question: 'What is React?',
        answer: 'A library for managing user interfaces'
      },
      {
        question: 'Where do you make Ajax requests in React?',
        answer: 'The componentDidMount lifecycle event'
      }
    ]
  },
  JavaScript: {
    title: 'JavaScript',
    questions: [
      {
        question: 'What is a closure?',
        answer: 'The combination of a function and the lexical environment within which that function was declared.'
      }
    ]
  }
}

这就是我需要的:

[
  { title: "React", questions: 2},
  { title: "JavaScript", questions: 1}
]

我已经尝试过Object.keys然后对其进行映射 - 这给了我一个新数组中的标题或问题。

标签: javascriptreactjsreact-nativeecmascript-6

解决方案


您可以映射Object.values并提取您需要的值。

const data = {
  React: {
    title: 'React',
    questions: [{
        question: 'What is React?',
        answer: 'A library for managing user interfaces'
      },
      {
        question: 'Where do you make Ajax requests in React?',
        answer: 'The componentDidMount lifecycle event'
      }
    ]
  },
  JavaScript: {
    title: 'JavaScript',
    questions: [{
      question: 'What is a closure?',
      answer: 'The combination of a function and the lexical environment within which that function was declared.'
    }]
  }
}

console.log(
  Object.values(data).map(({
    title,
    questions: {
      length: questions
    }
  }) => ({
    title,
    questions
  }))
)


推荐阅读