javascript - 如何在组中动态显示数组数组
问题描述
如何动态显示数组数组。嵌套数组有多个对象。我想分组显示它们。
var obj =
[
[
{ name: 'Text 1', title: 'Text 1 Title', category: 'Text 1' },
{ name: 'Text 2', title: 'Text 2 Title', category: 'Text 1' }
],
[
{ name: 'Text 1', title: 'Text 1 Title', category: 'Text 2' },
{ name: 'Text 2', title: 'Text 2 Title', category: 'Text 2' }
],
]
我的原始解决方案有效,但它全部显示在一行中
const list = obj.map(cat => cat.map(e => {
return (
<div className={e.category} key={`${e.title}-${e.name}`}>
<h6>{e.title}</h6>
<p>{e.name}</p>
</div>
)
}));
例如
Name: Text 1
Title: Text 1 Title
Name: Text 2
Title: Text 2 Title
Name: Text 1
Title: Text 1 Title
Name: Text 2
Title: Text 2 Title
我想像这样显示它们,例如
Text 1 Category
Name: Text 1
Title: Text 1 Title
Name: Text 2
Title: Text 2 Title
Text 2 Category
Name: Text 1
Title: Text 1 Title
Name: Text 2
Title: Text 2 Title
我试图在 div 中创建类别并给它们 id 然后渲染它们但想不出如何在正确的 div 中实现类别的解决方案
var objList = ["Text 1", "Text 2"];
const sectionList = objList.map((e, index) => {
return (
<div id={e} key={index}></div>
)
})
解决方案
Remake your obj
const reArray = {};
obj.forEach(parent => {
parent.forEach(child => {
const {name, title, category} = child;
if(reArray[category]) {
reArray[category].push({name, title})
} else {
reArray[category]=[{name,title}]
}
})
})
render
Object.keys(reArray).map(obj => {
return (
<div key={obj}>
<h6>{obj} Category</h6>
{reArray[obj].map(item => {
const {name, title} = item;
return (
<>
<p>Name :{name}</p>
<p>Title : {title}</p>
</>
)
})}
</div>
)
})
推荐阅读
- django - Django Model 的值为 NoneType 为什么?
- vue.js - 为什么我的道具没有被动态绑定?
- php - 尽管变量存在于已包含的文件中,但未定义的变量错误
- typescript - 客户端 Typescript 应用程序和 GraphQL 后端的一般工作流程是什么
- sql-server - 在不删除依赖项的情况下增加列中的小数位数
- youtube-api - 当用户不是内容所有者时如何列出频道
- r - 在 Shiny Dashboard 中选择菜单项时显示第二个菜单
- javascript - 使用 Immer 测试 redux reducer
- javascript - ReactJS:什么是“this.setState(defaultDogs);” 在这段代码中是什么意思?
- java - 如何使用 gson 库形成 json 以循环遍历对象、列表?