Home > front end >  How to display mapped data as list in react table
How to display mapped data as list in react table

Time:07-26

i want to show list of job id to single member id in react table

enter image description here

CodePudding user response:

function MyComponent() {
  const arr = [
    { memberId: 413, jobId: 42 },
    { memberId: 405, jobId: 52 },
  ];

  return (

    <div>
        <table>
            <tr>
                <th>Member id</th>
                <th>Job id</th>
            </tr>
            {arr.map((el) => {
                return(
                    <tr key={el.memberId}>
                        <td>{el.memberId}</td>
                        <td>{el.jobId}</td>
                    </tr>
                )
            })}
        </table>
    </div>
  );
}

CodePudding user response:

if you want to create a map member id to job ids, then you need to create a map structure:

function MyComponent() {
  const arr = [
    { memberId: 413, jobId: 42 },
    { memberId: 405, jobId: 52 },
  ];

  let memberIdToJobsMap = {};
  arr.forEach((el) => {
    memberIdToJobsMap[el.memberId] =  memberIdToJobsMap[el.memberId] || [];
    memberIdToJobsMap[el.memberId].push(el.jobId);
  });


  return (
    <div>
      {Object.keys(memberIdToJobsMap).map((memberId) => (
        <div key={memberId}>
          {memberId}:  {memberIdToJobsMap[memberId].join(", "))}
        </div>
      ))}
    </div>
  );
}

CodePudding user response:

You need to reformat your data.

const groupedData = {};

  data.forEach((row) => {
    if (!groupedData[row.memberId]) {
      groupedData[row.memberId] = [];
    }

    groupedData[row.memberId].push(row.jobId);
  });

Full Example:

const data = [
  { memberId: 414, jobId: 1 },
  { memberId: 404, jobId: 2 },
  { memberId: 414, jobId: 3 },
  { memberId: 411, jobId: 6 },
  { memberId: 412, jobId: 7 },
  { memberId: 404, jobId: 8 }
];

export default function App() {
  const tableHeader = Object.keys(data[0]);
  const groupedData = {};

  data.forEach((row) => {
    if (!groupedData[row.memberId]) {
      groupedData[row.memberId] = [];
    }

    groupedData[row.memberId].push(row.jobId);
  });

  return (
    <div>
      <table>
        <tr>
          {tableHeader.map((key) => (
            <th>{key}</th>
          ))}
        </tr>
        {Object.keys(groupedData).map((key) => (
          <tr>
            <td>{key}</td>
            <td>{groupedData[key].join(", ")}</td>
          </tr>
        ))}
      </table>
    </div>
  );
}

Here is a live example:

Edit objective-gagarin-480lzf

  • Related