Home > Enterprise >  Create dynamic table from array of objects in react
Create dynamic table from array of objects in react

Time:11-13

I have a object with 2 keys and each key has a value which is an array. Something like this,

this.obj = {
      SCIENCE: [
        {
          assigned_to_name: 'James B',
          assigned_date: '11/12/2022',
          key: 0,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
        {
          assigned_to_name: 'Johny P',
          assigned_date: '11/13/2022',
          key: 2,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
      ],
      ARTS: [
        {
          assigned_to_name: 'Sara B',
          assigned_date: '11/13/2022',
          key: 0,
          id: 'VMCYN',
          code: 'ARTS#1',
          title: 'Arts group',
        },
      ],
    };

Now I want to print each array separately.

 ------- ------- -------- 
| ID    | NAME  | CODE   |
 ------- ------- -------- 
| UID01 | James | SCI#01 |
 ------- ------- -------- 
| UID01 | John  | SCI#01 |
 ------- ------- -------- 

and

 ------- ------ --------- 
| ID    | NAME | CODE    |
 ------- ------ --------- 
| UID05 | Sara | ARTS#01 |
 ------- ------ --------- 

Here is the code that I have tried so far,

import React from 'react';
import ReactTable from 'react-table';

export default class App extends React.Component {
  constructor() {
    super();
    this.obj = {
      SCIENCE: [
        {
          assigned_to_name: 'James B',
          assigned_date: '11/12/2022',
          key: 0,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
        {
          assigned_to_name: 'Johny P',
          assigned_date: '11/13/2022',
          key: 2,
          id: 'Uto1O',
          code: 'SCI#01',
          title: 'Science group',
        },
      ],
      ARTS: [
        {
          assigned_to_name: 'Sara B',
          assigned_date: '11/13/2022',
          key: 0,
          id: 'VMCYN',
          code: 'ARTS#1',
          title: 'Arts group',
        },
      ],
    };
  }

  render() {
    return (
      <div>
        {(() => {
          if (Object.keys(this.obj).length > 0) {
            for (const key of Object.keys(this.obj)) {
              const headings = ['id', 'code', 'assigned_to_name'];
              let value = this.obj[key];
              console.log('value', key, this.obj[key]);
              return (
                <table className="table">
                  <thead className="thead-dark">
                    <tr>
                      {headings.map((heading) => (
                        <th>{heading}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {value.map((row) => (
                      <tr>
                        {headings.map((heading) => (
                          <td>{row[heading]}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              );
            }
          }

          return null;
        })()}
      </div>
    );
  }
}

And here is the link of the source https://stackblitz.com/edit/react-vucrsu?file=src/App.js

CodePudding user response:

You don't see the second table because it returns from the first iteration of the loop. Instead, you must accumulate the tables into an array and return them at the end.

Try like below:

class App extends React.Component {
  constructor() {
    super();
    this.obj = {
      SCIENCE: [
        {
          assigned_to_name: "James B",
          assigned_date: "11/12/2022",
          key: 0,
          id: "Uto1O",
          code: "SCI#01",
          title: "Science group"
        },
        {
          assigned_to_name: "Johny P",
          assigned_date: "11/13/2022",
          key: 2,
          id: "Uto1O",
          code: "SCI#01",
          title: "Science group"
        }
      ],
      ARTS: [
        {
          assigned_to_name: "Sara B",
          assigned_date: "11/13/2022",
          key: 0,
          id: "VMCYN",
          code: "ARTS#1",
          title: "Arts group"
        }
      ]
    };
  }

  render() {
    return (
      <div>
        {(() => {
          if (Object.keys(this.obj).length > 0) {
            const tables = [];
            for (const key of Object.keys(this.obj)) {
              const headings = ["id", "code", "assigned_to_name"];
              let value = this.obj[key];
              tables.push(
                <table className="table" key={key}>
                  <thead className="thead-dark">
                    <tr>
                      {headings.map((heading) => (
                        <th key={heading}>{heading}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {value.map((row, rowIndex) => (
                      <tr key={rowIndex}>
                        {headings.map((heading, index) => (
                          <td key={index}>{row[heading]}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              );
            }
            return tables;
          }

          return null;
        })()}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('.react'));
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

You can simplify the code like this using Object.values and Array.prototype.map:

class App extends React.Component {
  constructor() {
    super();
    this.obj = {
      SCIENCE: [
        {
          assigned_to_name: "James B",
          assigned_date: "11/12/2022",
          key: 0,
          id: "Uto1O",
          code: "SCI#01",
          title: "Science group"
        },
        {
          assigned_to_name: "Johny P",
          assigned_date: "11/13/2022",
          key: 2,
          id: "Uto1O",
          code: "SCI#01",
          title: "Science group"
        }
      ],
      ARTS: [
        {
          assigned_to_name: "Sara B",
          assigned_date: "11/13/2022",
          key: 0,
          id: "VMCYN",
          code: "ARTS#1",
          title: "Arts group"
        }
      ]
    };
  }

  renderTable = (key, value) => {
    const headings = ["id", "code", "assigned_to_name"];
    return (
      <table className="table" key={key}>
        <thead className="thead-dark">
          <tr>
            {headings.map((heading) => (
              <th key={heading}>{heading}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {value.map((row, rowIndex) => (
            <tr key={rowIndex}>
              {headings.map((heading) => (
                <td key={row[heading]}>{row[heading]}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    );
  };

  render() {
    return (
      <div>
        {Object.entries(this.obj).map(([key, value]) => this.renderTable(key, value))}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('.react'));
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

  • Related