简体   繁体   English

如何将嵌套数组转换为表 Javascript React

[英]How to convert nested array to Table Javascript React

I have a nested array, and want to convert it into a table in React.我有一个嵌套数组,并且想将其转换为 React 中的表。

For example, my data is represented as:例如,我的数据表示为:

data = [[a,b,c], [d,e,f], [g, h, i]]

and I would like to represent it as a table in React that looks something like:我想将它表示为 React 中的一个表,看起来像:

a d g

b e h

c f i

with each entry in the data list as a column, and the first entry in each nested list (a, d, and g in my case) as headers.将数据列表中的每个条目作为一列,并将每个嵌套列表中的第一个条目(在我的情况下为 a、d 和 g)作为标题。 I have been trying to use nested map functions, but have been unsuccessful我一直在尝试使用嵌套的 map 函数,但没有成功

Array.map() is your new best friend! Array.map()是你最好的新朋友!

First though, it is much easier to do rows first, then columns, so you'll want to reformat your data from首先,先做行,然后做列要容易得多,所以你需要重新格式化你的数据

[[a,b,c], [d,e,f], [g, h, i]]

to

[[a,d,g], [b,e,h], [c,f,i]]

After you've done this, you can use map() to iterate over each child array.完成此操作后,您可以使用map()遍历每个子数组。 Each child array will be its own <tr /> .每个子数组都是它自己的<tr /> Inside of the <tr /> you can iterate over each element in the child array, placing each inside of a <td /> .<tr />内部,您可以遍历子数组中的每个元素,将每个元素放在<td />内部。

The result might look something like this结果可能看起来像这样

// The data
const data = [[a,d,g], [b,e,h], [c,f,i]]

// Inside the component
<table>
    {
        data.map((row, index) => {
            return (
                <tr key={index}>
                    {
                        row.map((cell, index) => {
                            return <td key={index}>{cell}</td>
                        })
                    }
                </tr>
            )
        })
    }
</table>

Hopefully this helps!希望这会有所帮助!

You need a combination of reduce and map :您需要reducemap的组合:

 const datas = [["a","b","c"], ["d","e","f"], ["g", "h", "i"]]; const rows = datas.reduce((acc, data,i) => { // pick first data as key that going to be the header const key = data.shift(); // map the rest to define the row object const row = data.map((val, n) => { // add key to the existing row object if (i > 0) { acc[n][key] = val; return acc[n]; } // create new row object return { [key]: val }; }); // return row as accumulator return row },[]) console.log(rows)

Here the implementation on react-table v7这里是react-table v7的实现

 const { useCallback, useEffect, useMemo, useState } = React; const { useTable } = ReactTable; const tableData = [["a","b","c"], ["d","e","f"], ["g", "h", "i"]]; function App() { const columns = useMemo(() => [ { Header: 'Column A', accessor: 'a', }, { Header: 'Column D', accessor: 'd', }, { Header: 'Column G', accessor: 'g', }, ],[]); const data = useMemo(() => { return tableData.reduce((acc, data,i) => { const key = data.shift(); const row = data.map((val, n) => { if (i > 0) { acc[n][key] = val; return acc[n]; } return { [key]: val }; }); return row },[]) },[]); const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data }); return ( <div> <table {...getTableProps()}> <thead> {headerGroups.map(headerGroup => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <th {...column.getHeaderProps()}> {column.render('Header')} </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {rows.map((row, i) => { prepareRow(row) return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { return ( <td {...cell.getCellProps()}> {cell.render('Cell')} </td> ) })} </tr> ) })} </tbody> </table> </div> ) } ReactDOM.render(<App />, document.querySelector('.react'));
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/react-table@7.8.0/dist/react-table.development.js"></script> <div class='react'></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM