solomancode
solomancode

Reputation: 55

Combine sequence values

Suppose I have the following sequence A

  {a:0}        {b:1}        {c:2}
----o------------o------------o---------    [A]


  {a:0}      {a:0, b:1}   {a:0, b:1, c:2}
----o------------o------------o----------   [B]

how to combine values from sequence [A] to achieve the result in [B]?

I tried combineLatest() operator but it didn't work.

I need to combine the previous values each time a new values emitted

Upvotes: 1

Views: 39

Answers (1)

Reactgular
Reactgular

Reputation: 54801

You can use a scan to aggregate an object's properties.

const {of} = rxjs;
const {scan} = rxjs.operators;
   
of({a:0}, {b:1}, {c:2}).pipe(
    scan((acc, next) => ({...next, ...acc}), {})
).subscribe(value => console.log(value));
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/rxjs.umd.js"></script>

You can change the order of ({...next, ...acc}) to ({...acc, ...next}) if you want previous values to overwrite or if you want aggregated values to overwrite.

Upvotes: 2

Related Questions