0

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"}],
  };
3
  • can you show the original obj data structure? Commented Oct 31, 2021 at 14:45
  • what did you do so far? Share your workout and code snippet you tried so far Commented Oct 31, 2021 at 14:55
  • and explain about your expectaion. it's not clear, what is the column? Commented Oct 31, 2021 at 14:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.