I have an array of objects like:
const data: any[] = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 4 },
{ x: 4, y: 6 }
];
// get x as array
from(d).pipe(map(m => m.x), toArray()).subscribe(x => ...);
And would like to map it to something like below to use it in Plotly
{
x: [1,2,3,4],
y: [1,2,4,6]
}
Of course, I could duplicate the pipe above to get y values, but this would be different subscriptions. Is there another way to solve this?
Let's use some ES6 magic here. We will be making use of the spread syntax and Object.assign. In a way, we are sort of transposing this array of objects.
const data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 4 },
{ x: 4, y: 6 }
];
const result = Object.assign(...Object.keys(data[0]).map(key =>
({ [key]: data.map( o => o[key] ) })
));
console.log(result)