在React中转换对象的对象

时间:2018-06-17 13:33:57

标签: javascript reactjs react-native ecmascript-6

我是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然后映射它 - 这给了我一个新数组中的标题或问题。

3 个答案:

答案 0 :(得分:3)

您可以映射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
  }))
)

答案 1 :(得分:2)

Object.keys是要走的路。

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.'
      }
    ]
  }
};

const newArray = Object.keys(data).map((key) => {
  return {
    title: data[key].title,
    questions: data[key].questions.length
  }
});

console.log(newArray)

答案 2 :(得分:0)

使用lodash的 reduce 更清晰简单,因为它可以像数组一样迭代对象:

import { reduce } from 'lodash';

const newData = reduce(
  data,
  (acc, { title, questions }) => [
    ...acc,
    { title, questions: questions.length },
  ],
  []
);