我有一组对象,如:
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 => ...);
并希望将其映射到类似下面的内容,以便在Plotly
中使用它
{
x: [1,2,3,4],
y: [1,2,4,6]
}
当然,我可以复制上面的管道来获得y值,但这将是不同的订阅。还有另一种解决方法吗?
与RxJS无关,它只是简单的JS。
使用reduce
如下:
const data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 4 },
{ x: 4, y: 6 }
];
const plotly = data.reduce((p, n) => ({
x: [...p.x, n.x],
y: [...p.y, n.y]
}), {
x: [],
y: []
});
console.log(plotly);
请改用rxjs reduce
from(this.data).pipe(
reduce((acc, m) => {
acc.x.push(m.x);
acc.y.push(m.y);
return acc
}, {x: [], y: []})).subscribe(x => console.log(x));
我们在这里使用一些ES6魔法。我们将利用spread syntax和Object.assign。在某种程度上,我们有点转置这个对象数组。
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)