const myObj = {
a: [1, 2, 3],
b: [2, 4, 6],
c: [10, 20, 30]
}
Into
const myCollection = [
{a: 1, b: 2, c: 10},
{a: 2, b: 4, c: 20},
{a: 3, b: 6, c: 30}
]
I tried combinations of Object.entries
, Object.keys
and map
but I'm always finding myself iterating twice or more over myObj
and I'm not happy with any solution I came up with.
So what is the most efficient (in terms of time complexity) and elegant way that you can think to achieve that?
You could reduce the entries and map nested arrays.
const
object = { a: [1, 2, 3], b: [2, 4, 6], c: [10, 20, 30] },
result = Object
.entries(object)
.reduce((r, [k, a]) => a.map((v, i) => ({ ...r[i], [k]: v })), []);
console.log(result);