Coderops
Coderops

Reputation: 79

How to show object of arrays in table using Reactjs

I have an object that contains a list of arrays. I want to show each object in different columns using Reactjs. Here this object contains list of arrays, I want each array element, to display on different columns.

Like

**sunday** **Monday**
Emp1.        emp1
             emp2

let result = {
    sunday: [{id:1,name:"emp1"}],
    monday: [{id:1,name:"emp1"},{id:2,name:"emp2"}],
    tuesday: [{id:1,name:"emp1"},{id:3,name:"emp3"},{id:4,name:"emp4"}],
    wednesday: [{id:1,name:"emp1"}],
    thursday: [{id:1,name:"emp1"},{id:4,name:"emp4"}],
    saturday: [{id:5,name:"emp5"}],
    friday: [{id:7,name:"emp7"},{id:1,name:"emp1"},{id:4,name:"emp4"}],
  };

Upvotes: 0

Views: 257

Answers (1)

Ben Stephens
Ben Stephens

Reputation: 3371

If I've understood the question correctly the first thing you probably need to do is flip the data on the diagonal (I think there's a proper term for this but I can't remember it if there is). e.g.

let result = {
  sunday: [{id:1,name:"emp1"}],
  monday: [{id:1,name:"emp1"},{id:2,name:"emp2"}],
  tuesday: [{id:1,name:"emp1"},{id:3,name:"emp3"},{id:4,name:"emp4"}],
  wednesday: [{id:1,name:"emp1"}],
  thursday: [{id:1,name:"emp1"},{id:4,name:"emp4"}],
  saturday: [{id:5,name:"emp5"}],
  friday: [{id:7,name:"emp7"},{id:1,name:"emp1"},{id:4,name:"emp4"}],
};

const ordered_table_keys = 'sunday monday tuesday wednesday thursday friday saturday'.split(' ');

const max_item_count = (input) =>
  Math.max(
    ...Object.values(input).map((arr) => arr.length)
  );

const get_table_rows = (input) =>
  Array
    .from({ length: max_item_count(input) })
    .map(
      (row, index) => ordered_table_keys.map((day) => input[day][index]?.name ?? null)
    );

console.log( JSON.stringify(get_table_rows(result)) );

Then in React you should be able to do something like:

const MyTable = ({ result }) => {
  return <table>
    <thead>
      <tr>
        { ordered_table_keys.map((key) => (
          <th key={key}>{key}</th>
        )) }
      </tr>
    </thead>
    <tbody>
      { get_table_rows(result).map((row, r_index) => (
        <tr key={r_index}>
          { row.map((item, i_index) => (
            <td key={i_index}>{item}</td>
          )) }
        </tr>
      )) }
    </tbody>
  </table>;
};

to display the table.

Upvotes: 2

Related Questions