davidkrdona davidkrdona - 1 month ago 5
Javascript Question

How can i iterate this json with map in React to render it

Im trying to iterate this JSON so i can make a table, but as there is many headers and many data how can i go through without doing this.

const BBDDCustomer = {
ui_labels: {
name: 'Name',
address: 'address',
postalCode: 'Postal Code',
city: 'City',
country: 'Country',
telephone: 'Telephone',
email: 'Email',
modified: 'Modified',
delete: 'Delete'

},
data: [
{
name: 'n1',
address: 'a1',
postalCode: 'PC 1',
city: 'c 1',
country: 'cou 1',
telephone: 'tel 1',
email: 'em 1'
}
}


I don't have to write like this:

<table striped bordered condensed hover responsive>
<thead>
<tr>
<th>{BBDDCustomer.ui_labels.name}</th>
<th>{BBDDCustomer.ui_labels.address}</th>
<th>{BBDDCustomer.ui_labels.postalCode}</th>
<th>{BBDDCustomer.ui_labels.city}</th>
<th>{BBDDCustomer.ui_labels.country}</th>
<th>{BBDDCustomer.ui_labels.telephone}</th>
<th>{BBDDCustomer.ui_labels.email}</th>
<th>{BBDDCustomer.ui_labels.modified}</th>
<th>{BBDDCustomer.ui_labels.delete}</th>
</tr>
</table>

Answer

You need to enumerate properties in the order you want

const columns = ['name', 'address', ...];

and use map

<Table striped bordered condensed hover responsive>
      <thead>
       <tr>
           {
             columns.map(column => (
              <th key={column}>{BBDDCustomer.ui_labels[column]}</th>
            ))
           }
       </tr>
      </thead>
      <tbody>
        {
          BBDDCustomer.data.map((data, i) =>(
           <tr key={i}>
               {
                 columns.map(column => (
                    <td key={column + i}>{data[column]}</td>
                 ))
               }
           </tr>
          ))
        }
      </tbody>
</Table>