Rxjs - Flattening with transformation

Asked by At

I have a simple problem that I don't really know how to handle with Rxjs.

The API is returning an array similar to this :

[
  {
    name : test1,
    code : [1, 2]
  },
  {
    name : test2,
    code : [1, 2, 3]
  },
  ...
]

And I would like to return something like this with the help of Rxjs :

[
  {
    name : test1,
    code : 1
  },
  {
    name : test1,
    code : 2
  },
  {
    name : test2,
    code : 1
  },
  {
    name : test2,
    code : 2
  },
  {
    name : test2,
    code : 3
  },
  ...
]

It's obviously possible with a combination of transformation, but I can't get my head around it.

1 Answers

2
PierreDuc On Best Solutions

You don't really need rxjs for this, just the map operator. You can achieve this by using the reduce function from Array:

untested code, but you get the idea

this.callToApi().pipe(
  map(data => data.reduce((acc, cumm) => {
    acc.push(
      ...cumm.code.map(code => ({ name: cumm.name, code }))
    );
    return acc;
  }, []))
).subscribe(data => {
  console.log(data);
});