Estoy tratando de hacer un bucle de los datos de json y mostrarlos en la tabla. Estoy teniendo variedad de objetos. Tengo 3 valores en mi archivo json, necesito mostrar los tres datos en celdas individuales, la tercera columna está en formato de matriz. Entonces, la estructura de mi json es una matriz de objetos y dentro del objeto, mi tercera columna es nuevamente una matriz. Estoy tratando de obtener todos los datos dinámicamente, pero cuando uso el método de mapa no puedo obtener los valores. Por lo tanto, intenté usar Object.Values y forEach, y obtengo los valores según la posición. ¿Puede alguien ayudarme a obtener todos los datos dinámicamente? Gracias por adelantado. He pegado el código y los datos simulados a continuación. ¡Gracias por adelantado!
//I need to display the values in below table component. const Table = () => ( <Table> <Header> <HeaderCell key="NAME">Contact Name</HeaderCell> <HeaderCell key="ContactID">Contact ID</HeaderCell> <HeaderCell key="contactGrp">Contact Group</HeaderCell> </Header> <Body> <Row key="conact-0"> <Cell key="NAME">ABC</Cell> <Cell key="ContactID">123</Cell> <Cell key="contactGrp">[1, 2]//In badge format</Cell> </Row> </Body> </Table> ); //Table PROPS- Prop: Children Type: Node (the child content for table consisting of eithera Table Header or Body) //Table Header Props- Prop: Children Type: node //Table Row Props - Prop: Children Type: node (child tablecells to be placed within the tr) //Table Cell Props - Prop: Children Type: node (content to be displayed for row cell) //My Code Const customTable = ({mockData})=> { return ( <Table> <Header> <HeaderCell key="Name"> Contact Name</HeaderCell> <HeaderCell key="ID"> Contact ID</HeaderCell> <HeaderCell key="Group"> Contact Group</HeaderCell> </Header> <Body> { mockData.forEach((element) => { console.log(element.key); element.cells.forEach(cell => { <Row key={cell.key}> <Cell key={cell.key}>{cell.contactName}</Cell>////Here I am not getting the Data <Cell key={cell.key}>{cell.contactID}</Cell>//Here I am not getting the Data </Row> }) }) } </Body> //MOCK DATA const mockData = [ { "key":"row-0", "cells":[ { key: 'cell-0', id: 'ID-0', headerName:'contactname', contactName: 'ABC' }, { key: 'cell-1', id: 'ID-1', headerName: 'contactID', contactID:'123' }, { key: 'cell-3', id: 'ID-3', headerName: 'contactGrp', contactGroup: ['A', 'B']} ] } ];Es más fácil dividirlo en pasos dentro de los límites del componente. Este ejemplo utiliza tres funciones para encontrar los encabezados, todas las filas y las celdas para cada una de esas filas.
function Example({ data }) { // Return a list of the headings function getHeadings(data) { return data[0].cells.map(h => { return <th>{h.headerName}</th>; }); } // Return the cells for a single row // making sure that each element of the // the array in `contactGroup` is created // from a Badge component function getRow(cells) { return cells.map(cell => { const { headerName } = cell; if (Array.isArray(cell[headerName])) { return ( <td> {cell[headerName].map(el => { return <Badge text={el} />; })} </td> ); } return <td>{cell[headerName]}</td>; }); } // Get all the rows function getRows(data) { return data.map(row => { return <tr>{getRow(row.cells)}</tr>; }); } return ( <table> <thead>{getHeadings(data)}</thead> <tbody>{getRows(data)}</tbody> </table> ); } // Badge component function Badge({ text }) { return ( <div className="badge">{text}</div> ); } const data=[{key:"row-0",cells:[{key:"cell-0",id:"ID-0",headerName:"contactName",contactName:"ABC"},{key:"cell-1",id:"ID-1",headerName:"contactID",contactID:"123"},{key:"cell-3",id:"ID-3",headerName:"contactGroup",contactGroup:["A","B"]}]},{key:"row-1",cells:[{key:"cell-1-0",id:"ID-1-0",headerName:"contactName",contactName:"DEF"},{key:"cell-1-1",id:"ID-1-1",headerName:"contactID",contactID:"456"},{key:"cell-1-3",id:"ID-1-3",headerName:"contactGroup",contactGroup:["C","D"]}]}]; ReactDOM.render( <Example data={data} />, document.getElementById('react') ); table { border-collapse: collapse; border; 1px solid #565656; } thead { background-color: #efefef; text-transform: uppercase; } td, th { padding: 0.5em; border:1px solid #cdcdcd; } .badge { display: inline; padding: 0.2em 0.4em; background-color: #87CEFA; border: 1px solid #343434; border-radius: 5px; } .badge:not(:last-child) { margin-right: 0.4em; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>Esto no es tan difícil de hacer e incluso no necesita utilizar Object.values primero. Simplemente haga un .forEach en el objeto mismo y dentro del bucle haga otro .forEach en los elementos devueltos de la ejecución anterior de .forEach .
Por ejemplo:
const mockData = [{ "key": "row-0","cells": [{ key: 'cell-0', id: 'ID-0', headerName: 'contactname', contactName: 'ABC' }, { key: 'cell-1', id: 'ID-1', headerName: 'contactID', contactID: '123' }, { key: 'cell-3', id: 'ID-3', headerName: 'contactGrp', contactGroup: ['A', 'B'] } ] }]; mockData.forEach((element) => { console.log(element.key); element.cells.forEach(cell => { console.log(cell.key, cell.id); }); });los valores clave entre los elementos hermanos deben ser únicos para que se representen correctamente.
¡Dentro de su element.cells.forEach los 2 <Cell> s tienen la misma clave!
Hazlo:
<Cell key={cell.key + 'contactName' }>{cell.contactName}</Cell> <Cell key={cell.key + 'contactId' }>{cell.contactID}</Cell>