Search code examples
javascriptarraysobjecttranspose

How do I transpose rows to columns in a array of values?


My data structure looks like this:

var data = [
    { 
    A:[
    {name: 'Test1', amount: 20},
    {name: 'Test2', amount: 30}
    ], 
    B:[
    {name: 'Test3', amount: 40},
    {name: 'Test4', amount: 50}
    ] 
    },
    {
    A:[
    {name: 'Test1', amount: 200},
    {name: 'Test2', amount: 300}
    ], 
    B:[
    {name: 'Test3', amount: 400},
    {name: 'Test4', amount: 500}
    ]}
  ]

Here is how I would like to transpose my structure: enter image description here

I also created my array structure in JSFiddle: https://jsfiddle.net/rj5e38v9/3/


Solution

  • You can use array reduce and create a object with keys A & B. Then you can iterate this object to create the table

    var data = [{
        A: [{
            name: 'Test1',
            amount: 20
          },
          {
            name: 'Test2',
            amount: 30
          }
        ],
        B: [{
            name: 'Test3',
            amount: 40
          },
          {
            name: 'Test4',
            amount: 50
          }
        ]
      },
      {
        A: [{
            name: 'Test1',
            amount: 200
          },
          {
            name: 'Test2',
            amount: 300
          }
        ],
        B: [{
            name: 'Test3',
            amount: 400
          },
          {
            name: 'Test4',
            amount: 500
          }
        ]
      }
    ]
    
    const val = data.reduce((acc, curr) => {
      for (let keys in curr) {
        if (!acc.hasOwnProperty(keys)) {
          acc[keys] = [];
        }
        acc[keys].push(...curr[keys])
    
      }
      return acc;
    }, {});
    
    let tableStr = ''
    for (let keys in val) {
      tableStr += `<ul>
      <li class="headerList">${keys}</li>
      ${val[keys].map(elem=>{return '<li><span>'+elem.name+'<span class="valCol">'+elem.amount+'</span></li>'})}
      
     </ul>`
    }
    
    
    document.getElementById('dataDisplay').innerHTML = tableStr
    li {
      list-style-type: none
    }
    
    .valCol {
      margin-left: 50px;
      color: green;
    }
    
    .headerList {
      font-style: bold;
      font-size: 50px;
    }
    <div id="dataDisplay">
    
    
    </div>