1

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

Wow, I have to check out what is happening inside this magic. But I had to add the target Object.assign({},... to compile it. Thank you!
@alex555 Yeah, I admit this one might be a bit hard to read! trichetriche's solution seems the most readable amongst all the answers here!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.