I'm trying to do some mapping/reducing on some javascript object and failing miserably.
The data as it comes from the backend comes in looking something like this:
[
{table:"a1", data: {colA:1,colB:2,colC:3}},
{table:"a2", data: {colA:2,colB:3,colC:4}},
{table:"a3", data: {colA:3,colB:4,colC:5}}
]
Recharts needs the data in the following format (make the source data keys as the unique "name" key for the result)
[
{name: 'colA', a1: 1, a2: 2, a3: 3},
{name: 'colB', a1: 2, a2: 3, a3: 4},
{name: 'colC', a1: 3, a2: 4, a3: 5}
]
My current solution is currently O(n^n) because I'm building an result object, and looping over it every time. I'm using ECMA6/Babel as well as Lodash. Any guidance would be greatly appreciated! Thanks!
Edit: Here's my current solution
var dest = []
Lodash.forEach(source,(o) => {
var table = o.table;
Lodash.forEach(o.data, (p,q) => {
// See if the element is in the array
const index = Lodash.findIndex(dest,(a) => {return a.name === q});
if ( index === -1) {
var obj = {};
obj[table] = Number(p);
obj.name = q;
dest.push(obj);
} else {
dest[index][table] = Number(p);
}
})
});
for.O(n² m), notO(n^n)