如何在Angular 6中将多个属性映射到数组?

问题描述 投票:1回答:3

我有一组对象,如:

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值,但这将是不同的订阅。还有另一种解决方法吗?

angular rxjs rxjs-pipeable-operators
3个回答
3
投票

与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);

0
投票

请改用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));

https://stackblitz.com/edit/angular-gldpxy


0
投票

我们在这里使用一些ES6魔法。我们将利用spread syntaxObject.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)
© www.soinside.com 2019 - 2024. All rights reserved.