首页 > 解决方案 > 如何在组中动态显示数组数组

问题描述

如何动态显示数组数组。嵌套数组有多个对象。我想分组显示它们。

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>
   )
})

标签: javascriptreactjs

解决方案


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>
    )
})

推荐阅读