Creating dynamic table, Object.keys not allowing to return rows of table react

Viewed 65

I am creating a dynamic table. If I writing a function like this:-

function renderTable(Category) {
  return (
    <table>
      <tr>
        <th>Status</th>
        <th>Name</th>
        <th>Product</th>
      </tr>
      {data.data.changer.map(changer=> {
        const valuePresent = changer.attack.find(
          x => x.unique === category.name
        );
        if (valuePresent) {
          return (
            <tr>
              <td>{changer.rule_status}</td>
              <td>{changer.vendor_rule_name}</td>
              <td>{changer.firewall_vendor}</td>
            </tr>
          );
        }
      })}
    </table>
  );
}

It returns the perfect table of how I need it.

But If I try to make the key as dynamic as well like:-

function renderTable(Category) {
  return (
    <table>
      <tr>
        <th>Status</th>
        <th>Name</th>
        <th>Product</th>
      </tr>
      {Object.keys(data.data).forEach((key, index) => {
        if (Category=== key) {
          {
            data.data[key].map(changer=> {
              const valuePresent = changer.attack.find(
                x => x.unique === category.name
              );
              if (valuePresent) {
                return (
                  <tr>
                    <td>{changer.rule_status}</td>
                    <td>{changer.vendor_rule_name}</td>
                    <td>{changer.firewall_vendor}</td>
                  </tr>
                );
              }
            });
          }
        }
      })}
    </table>
  );
}

it does not return rows, or and Any Idea why I want to make key's as well dynamic

1 Answers

Array.prototype.forEach() doesn't return anything, so the JSX in your inner map are never returned. If your goal is to only render the data with the property coverageCategory, I would instead get that property and then do the the map like you have initially, e.g.:

function renderTable(coverageCategory) {
  const data = coverageData.data[coverageCategory];

  return (
    <table>
      <tr>
        <th>Rule Status</th>
        <th>Rule Name</th>
        <th>Product name</th>
      </tr>
      {data.firewall.map(firewall => {
        const valuePresent = firewall.mitre_attack.find(
          x => x.technique === categorySelected.name
        );
        if (valuePresent) {
          return (
            <tr>
              <td>{firewall.rule_status}</td>
              <td>{firewall.vendor_rule_name}</td>
              <td>{firewall.firewall_vendor}</td>
            </tr>
          );
        }
      })}
    </table>
  );
}

An improvement would also be to filter:

data.firewall
  .filter((firewall) =>
    firewall.mitre_attack.some((x) => x.technique === categorySelected.name)
  )
  .map((firewall) => (
    <tr>
      <td>{firewall.rule_status}</td>
      <td>{firewall.vendor_rule_name}</td>
      <td>{firewall.firewall_vendor}</td>
    </tr>
  ));
Related