javascript - 在 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
然后对其进行映射 - 这给了我一个新数组中的标题或问题。
解决方案
您可以映射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
}))
)
推荐阅读
- c# - 托管在 Azure 上的 asp.net、EF6、Web 表单应用程序上偶尔出现“EntityValidationErrors”,需要重新启动服务器?
- javascript - “无法读取 null 的属性‘过滤器’”(与我在这里看到的其他解决方案略有不同)
- java - 需要帮助解释 Java 线程转储
- jquery - 在 NodeJS-Express 应用程序的 DOM 操作中使用 jQuery
- ios - 在领域中存储值
- php - DevTools 中的错误不再显示 XHR 响应
- python - 我无法下载 cv2,无论出于何种原因它都不起作用
- image - tensorflow仿射变换填充值
- html - 如何将跨度与h2放在同一行?
- python - 使用基本用户名和密码通过 Python 从 CloudFront 下载文件