Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
crear una tabla a partir del objeto JSON en reaccionar

Estoy creando una tabla dinámicamente en React con la respuesta de la API tal como se recibe.

 data = {"name":"tom", "age":23, "group":null, "phone":xxx}

Funciona bien con eso, pero la clave de grupo a veces contiene otro objeto, por lo que quiero crear una subtabla siempre que haya otro objeto dentro de una clave.

Por ejemplo:

 data = {"name":"tom", "age":23, "group":{"id":123, "joined_at":12-jan-2022}, "phone":xxx}

Mi código actual es:

 <table> {Object.keys(data).map(index=> ( <tr> <td>{index}</td> <td>{data[index]?.toString()}</td> </tr> ))} </table>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El código que ha compartido cambiaría de la siguiente manera:

 <table> {Object.keys(data).map((item, index) => { if (group) { return ( <> <tr> <td>{index}</td> <td>{item.toString()}</td> </tr> <tr> <table> <tr> <td>{group.id}</td> <td>{group.joined_at}</td> </tr> </table> </tr> </> ); } return ( <tr> <td>{index}</td> <td>{item.toString()}</td> </tr> ); })} </table>;

Puede corregir el formato según sus necesidades, pero esta es esencialmente la forma en que crearía una subtabla basada en el valor del group .

Una versión ligeramente mejorada sería:

 const normalTableRow = (index, item) => { return ( <tr> <td>{index}</td> <td>{item.toString()}</td> </tr> ); }; <table> {Object.keys(data).map((item, index) => { if (group) { return ( <> {normalTableRow(index, item)} <tr> <table> <tr> <td>{group.id}</td> <td>{group.joined_at}</td> </tr> </table> </tr> </> ); } return normalTableRow(index, item); })} </table>;

EDITAR: actualización de la solución basada en el comentario

 const normalTableRow = (index, item) => { return ( <tr> <td>{index}</td> <td>{item.toString()}</td> </tr> ); }; const isObject = (value) => { return typeof value === 'object' && !Array.isArray(value) && value !== null; }; <table> {Object.keys(data).map((item, index) => { let subTables = Object.keys(item).map((key) => { if (isObject(item[key])) { return ( <tr> <table> <tr> {Object.keys(item[key]).map((subKey) => { return <td>{item[key][subKey]}</td>; })} </tr> </table> </tr> ); } }); return ( <> {normalTableRow(index, item)} {[...subTables]} </> ); })} </table>;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!