Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert Object arrays into collection in Javascript

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?

like image 894
baba-dev Avatar asked Feb 10 '26 04:02

baba-dev


1 Answers

Just in case you'd need variable length:

const myObj = {
  a: [1, 2, 3],
  b: [2, 4, 6,8, 10],
  c: [10, 20, 30, 40],
};

let myCollection = [];

Object.keys(myObj).forEach((k) => {
  for (let i = 0; i < myObj[k].length; i++) {
    if (!myCollection[i]) myCollection.push({});
    myCollection[i][k] = myObj[k][i];
  }
});
console.log(myCollection);
like image 65
malarres Avatar answered Feb 16 '26 16:02

malarres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!