alex555
alex555

Reputation: 1786

How to map multiple properties to arrays in Angular 6?

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?

Upvotes: 1

Views: 4587

Answers (3)

wentjun
wentjun

Reputation: 42546

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)

Upvotes: 0

user4676340
user4676340

Reputation:

Not related to RxJS, it's just plain JS.

Use reduce as follows :

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

Upvotes: 3

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

Use rxjs reduce instead

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

Upvotes: 0

Related Questions