deepak murthy
deepak murthy

Reputation: 411

Dynamic table values from array of objects in react 17.0.01

I have array of object in the below format.

[0: {Number: "11080", Cost1: "354", Cost2: "354", Cost3: "354", quantity: "2000"}]

How do show this array of objects inside a table

Here is my required table structure - https://jsfiddle.net/deepakmurthy/Lhv2sk9d/

 {
      newFilteredArray?.map((value) => {
          return(
              <tr>
              <td>Name</td>
              <td>{quantity}</td>
              <td>{Cost}</td>
              <td>xxx</td>
              <td>xxx</td>
              <td>xxx</td>
              <td>xxx</td>
              </tr>
          );
  })

Upvotes: 0

Views: 38

Answers (1)

pilchard
pilchard

Reputation: 12919

If you're going to have more data in your array you might consider refactoring it before mapping, but as James mentioned in the comments you can simply add three rows per iteration.

The example below isolates the Cost{n} properties using destructuring, then maps the Object.keys() to return one row per key.

{
  data.map(({ Number, quantity, ...costs }) => {
    return (Object.keys(costs).map(key => (
      <tr>
        <td>{key}</td>
        <td>{quantity}</td>
        <td>{costs[key]}</td>
        <td>xxx</td>
        <td>xxx</td>
        <td>xxx</td>
        <td>xxx</td>
      </tr>))
    )
  })
}

const App = () => {

  const data = [{ Number: "11080", Cost1: "354", Cost2: "354", Cost3: "354", quantity: "2000" }]

  return (
    <table className="table table-striped bsictable" border="1" style={{ border: '#cdcdcd solid 1px' }}>
      <thead>
        <tr align="center">
          <th rowspan="2">Name</th>
          <th colspan="2">New </th>
          <th colspan="2">Pending</th>
          <th colspan="2">Completed </th>
        </tr>
        <tr align="center">
          <th>Quantity</th>
          <th>Cost</th>
          <th>Quantity</th>
          <th>Cost</th>
          <th>Quantity</th>
          <th>Cost</th>

        </tr>
      </thead>
      <tbody>
        {
          data.map(({ Number, quantity, ...costs }) => {
            return (Object.keys(costs).map(key => (
              <tr>
                <td>{key}</td>
                <td>{quantity}</td>
                <td>{costs[key]}</td>
                <td>xxx</td>
                <td>xxx</td>
                <td>xxx</td>
                <td>xxx</td>
              </tr>))
            )
          })
        }
      </tbody>
    </table >
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions