so I have a data structure that looks like this :
data = {
a: [1, 2, 3, 4, 5],
b: ["a", "b", "c", "d", "e"],
c: ["123", "235423", "12312", "1231", "12312"],
d: ["aa", "bb", "cc", "dd", "ee"],
...
}
and I need to convert it into a following structure:
[
{ a: 1, b: "a", c: "123", d: "aa", ... },
{ a: 2, b: "b", c: "235423", d: "bb", ... },
{ a: 3, b: "c", c: "12312", d: "cc", ... },
{ a: 4, b: "d", c: "1231", d: "dd", ... },
{ a: 5, b: "a", c: "12312", d: "ee", ... },
]
the number of keys in data can vary, but the length of the values will always be same across all arrays, i.e. data[a].length === data[z].length will always be true.
My solution:
const doStuff = () => {
const result = [];
const keys = Object.keys(data);
if (!keys) return result;
const valuesLength = keys[0].length
const result = [];
for (let i = 0; i < valuesLength ; i++) {
const obj = {};
for (const key in data) {
obj[key] = data[key][i];
}
result.push(obj);
}
return result;
};
is using two for loops is not most effective one since the number of keys can be large, so i'm looking for a most optimal solution