Search code examples
javascripttypescriptjavascript-objectstranspose

How to "transpose" Objects in TypeScript


Is there a way to nicely convert from an object:

Key_1 : {Head_1 : "val_11", Head_2 : "val_21", Head_3 : "val_31"}
Key_2 : {Head_1 : "val_12", Head_2 : "val_22", Head_3 : "val_32"}
Key_3 : {Head_1 : "val_13", Head_2 : "val_23", Head_3 : "val_33"}

to:

Head_1 : {Key_1 : "val_11", Key_2 : "val_12", Key_3: "val_13"}
Head_2 : {Key_1 : "val_21", Key_2 : "val_22", Key_3: "val_23"}
Head_3 : {Key_1 : "val_31", Key_2 : "val_32", Key_3: "val_33"}

In TypeScript?

Thanks a lot!


Solution

  • You can use "for..of" and "Object.entries" like below to transpose

    BTW, it's always better to write your approach/what have you tried in OP so that fellow users see where you are heading towards

    var obj = {
      Key_1 : {Head_1 : "val_11", Head_2 : "val_21", Head_3 : "val_31"},
      Key_2 : {Head_1 : "val_12", Head_2 : "val_22", Head_3 : "val_32"},
      Key_3 : {Head_1 : "val_13", Head_2 : "val_23", Head_3 : "val_33"}
    }
    
    function transpose(obj) {
      let newObj = {}
      for(let [key, value] of Object.entries(obj)) {
        for(let [k, v] of Object.entries(value)) { 
           newObj[k] = newObj[k] || {}
           newObj[k][key] = v
        }
      }
      return newObj
    }
    
    console.log(transpose(obj))