Home > Software design >  Mapping through array of objects doesn't work in Table component
Mapping through array of objects doesn't work in Table component

Time:07-23

In a React project, I have a table component which gets array of array structured JSON data and works fine, but, how could it done for array of objects structured JSON data. Following is the code for reference

Below is the array of array JSON data

const store_grid_data = {
    data: [
      [
        { id: 1 },
        false,
        "McDonalds",
        "Burger Store",
        "Mike John",
        "YYYY/MM",
        "Best Food Chain"
      ],
      [
        { id: 2 },
        false,
        "KFC",
        "Chicken Food Store",
        "Rock Wills",
        "YYYY/MM",
        "Best Food Chain Globally"
      ]
    ],
    page_info: {
      total_pages: 5,
      current_page: 1
    }
  };

Here I initialize and also set it

  let GridConfig = {};
  let grid_data = {};

  GridConfig = TableConfig;
  grid_data = store_grid_data;

  const [gridConfigData, setGridConfigData] = useState(GridConfig);
  const [gridData, setGridData] = useState(grid_data);

return (
    <>
      <Grid GridConfig={gridConfigData} GridData={gridData} />
    </>
  );

Below is the Columns section of Table

const TableConfig = {
  column_config: [
    {
      title: "",
      col_span: 1,
      sorted_order: "None",
      data_type: "check_box",
      cell_click_callback: true
    },
    {
      title: "Company",
      col_span: 1,
      sorted_order: "None",
      data_type: "text",
      cell_click_callback: false
    },
    {
      title: "Desc",
      col_span: 1,
      sorted_order: "None",
      data_type: "text",
      cell_click_callback: false
    }
  ]
};

export default TableConfig;

And now the entire Table structure

let colConfig = props.GridConfig.column_config;
  let gridData = props.GridData.data;

  return (
    <div className="table-responsive pt-3">
      <table className="table table-bordered table-striped" width="100%">
        <thead>
          <tr>
            {colConfig.map((d, key) => {
              return (
                <th key={key} colSpan={d.col_span} className={d.title_class}>
                  {d.title}
                </th>
              );
            })}
          </tr>
        </thead>
        <tbody>
          {gridData.map((rowData, rIndex) => {
            return (
              <tr
                key={`tr_${rowData[0].id}`}
                className={rowData[0].row_properties}
              >
                {rowData.slice(1).map((colData, cIndex) => {
                  return (
                    <td
                      key={`td_${rIndex}_${cIndex}`}
                      className={colConfig[cIndex].data_col_class}
                    >
                      {colConfig[cIndex].data_type === "text" &&
                        colConfig[cIndex].cell_click_callback && (
                          <div>
                            <a
                              onClick={() =>
                                clickCallback(
                                  colConfig[cIndex].title,
                                  cIndex   1,
                                  rowData[0].id
                                )
                              }
                            >
                              {" "}
                              {colData}{" "}
                            </a>
                          </div>
                        )}
                      {colConfig[cIndex].data_type === "text" &&
                        !colConfig[cIndex].cell_click_callback && (
                          <div>{colData}</div>
                        )}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

I want to set data with array of objects as

const newStoreData = {
    data: [
      {
        id: 252,
        compName: "Burger King",
        desc: "Burger Store",
        franchise: "Harry Tyson",
        estDate: "2020/11",
        feedBack: "Best Burgers"
      },
      {
        id: 321,
        compName: "Starbucks",
        desc: "Coffee Store",
        franchise: "George Speilsberg",
        estDate: "2018/04",
        feedBack: "Best Coffee"
      }
    ],
    page_info: {
      total_pages: 10,
      current_page: 1
    }
  };

What could be the best solution to tackle this. Any suggestion highly appreciated

Please refer Codesandbox link: https://codesandbox.io/s/bold-boyd-2e16j6

CodePudding user response:

I think that simply changing the way you point to the properties and changing the second map of the table so you can use it in a JSON would do the trick.

Something like this:

        <tbody>
          {gridData.map((rowData, rIndex) => {
            return (
              <tr key={`tr_${rowData.id}`}>
                {Object.keys(rowData).map((key, cIndex) => {
                  return (
                    <td
                      key={`td_${rIndex}_${cIndex}`}
                      className={colConfig[cIndex].data_col_class}
                    >
                      {colConfig[cIndex].data_type === "text" &&
                        colConfig[cIndex].cell_click_callback && (
                          <div> {rowData[key]} </div>
                        )}
                      {colConfig[cIndex].data_type === "text" &&
                        !colConfig[cIndex].cell_click_callback && (
                          <div>{rowData[key]}</div>
                        )}
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>

Note that in this example I used "old" syntax. You can find more recent syntax in the following post.

  • Related