Home > front end >  Combine Array and a Nested Array in React
Combine Array and a Nested Array in React

Time:02-24

I wanted to combine the parent array and its child array in one table. The child array should have background color of green.

I have a difficulty doing it?

Please check my codesandbox enter image description here

CodePudding user response:

Make an array which flattens your rows and their childrens too into single array. And add conditional fname and mname render for both cases handling in TableRow.

import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { styled } from "@mui/material/styles";

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: "lightgreen"
  },
  [`&.${tableCellClasses.body}`]: {
    backgroundColor: "lightgreen"
  }
}));

const rows = [
  {
    id: "111",
    fname: "Thomas",
    mname: "James",
    personnels: [
      {
        id: 1234,
        person_id: "233",
        parent_id: "111",
        person: {
          id: "233",
          fname: "Robert",
          mname: "Williams"
        }
      }
    ]
  },
  {
    id: "222",
    fname: "Jane",
    mname: "Doe",
    personnels: [
      {
        id: 4567,
        person_id: "333",
        parent_id: "222",
        person: {
          id: "333",
          fname: "James",
          mname: "Quincy"
        }
      }
    ]
  }
];

export default function BasicTable() {
  const arr=[...rows,...rows.map((e)=>e.personnels).flat()];
  console.log(arr)
  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>Fname</TableCell>
            <TableCell>Mname</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
        {arr.map((row) => (
              <TableRow
                key={row?.fname || row?.person?.fname}
                sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
              >
              {row?.fname ? (
            <TableCell>{row?.fname}</TableCell>
          ) : (
            <StyledTableCell>{row?.person?.fname}</StyledTableCell>
          )}
                {row?.mname ? (
            <TableCell align="right">{row?.mname}</TableCell>
          ) : (
            <StyledTableCell align="right">
              {row?.person?.mname}
            </StyledTableCell>
          )}
              </TableRow>
            ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

Code sandbox link: enter image description here

  • Related