Search code examples
javascriptarraysobjectlodashtransform

transform a specific object format to a dataset format


I got such an object with a specific format like this:

const o = {
  a: [1, 4],
  b: [2, 5],
  c: [3, 6],
  ...
}

Then i need to transform it to an dataset format like this:

const data = [
  { a:"1", b:"2", c:"3" },
  { a:"4", b:"5". c:"6" },
  ...
]

I am wondering is there any built in functions in lodash could implement this scenario or i could just easily do it by myself?


Solution

  • Using Object.assign()

    const o = {a: [1, 4], b: [2, 5], c: [3, 6]}
    
    const r = []
    
    for (let k in o)
      o[k].forEach((v, i) => 
        r[i] = Object.assign(r[i] || {}, {[k]: v}))
    
    console.log(r)