-1

I want to switch rows to columns , please provide javascript or react js format . Thank you

            const dataArray = [
              { product: "Product 1", year: "2009", sales: "1212" },
              { product: "Product 2", year: "2009", sales: "522" },
              { product: "Product 3", year: "2010", sales: "1337" },
            ];

//App.js

    function App() {

      const renderOriginalTable = (data, index) => {
        return (
          <tr key={index}>
            <td>{data.product}</td>
            <td>{data.year}</td>
            <td>{data.sales}</td>
          </tr>
        )
      };

      return (
        <div className="container">
          <h2>Original Table</h2>
          <table className="originalTable">
            <thead>
              <tr>
                <th>Product</th>
                <th>Year</th>
                <th>Sales</th>
              </tr>

            </thead>
            <tbody>{dataArray.map(renderOriginalTable)}</tbody>
          </table>

        </div>
      );
    }

    export default App

According to the code above, table will be as below :

   Product   | Year | Sales
   Product 1 | 2009 | 1212
   Product 2 | 2009 | 522
   Product 3 | 2010 | 1337

But I want the same data to be dispalyed as

 Product | Product 1 | Product 2 | Product 3
 Year    | 2009      | 2009      | 2010
 Sales   | 1212      | 522       | 1337

by converting rows into columns from the above mentioned jsan data.

Thank You

Krishna
  • 31
  • 5

2 Answers2

1

You might not be able to change the orientation just by using JavaScript. You have to restructure the table and use some CSS to change the orientation. First, remove the thead and move the tr with the th inside tbody:

<tbody>
  <tr>
    <th>Product</th>
    <th>Year</th>
    <th>Sales</th>
  </tr>
  {dataArray.map(renderOriginalTable)}
</tbody>

Then use CSS flexbox to change the table orientation:

tbody {
  display: flex;
  position: relative;
  align-items: stretch;
}

tr {
  flex-basis: 33.33333333%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  padding: 5px 10px;
}

th,
td {
  flex-basis: 100%;
  text-align: left;
  display: flex;
  padding: 2px;
}

Live example @Codesandbox

You can other CSS solutions here.

Shahid
  • 145
  • 10
1
        <table className="originalTable">
       
          <tr>
            <th>Product</th>
            {dataArray.map((item, index) => {
             <td>{item.product}</td>
             })}
          </tr>

          <tr>
            <th>Year</th>
            {dataArray.map((item, index) => {
             <td>{item.year}</td>
             })}
          </tr>

          <tr>
            <th>Sales</th>
          {dataArray.map((item, index) => {
             <td>{item.sales}</td>
             })}
          </tr>

       
       
      </table>

try something like this, this might work

Shivam
  • 370
  • 2
  • 6