Tombery
Tombery

Reputation: 296

Concatenate previous and new value of arrays inside an object in an Observable

I have an object with an array of items in it something like this: { a: string, b: string, items: Something[] }. In my observable, when a new value is emitted, I want the previous values of items to be concatenated with new values so I used the scan operator. It does something like myObservable$.pipe(scan((acc: any, curr: any) => [...acc.items, ...curr.items])).

It is working as expected, but I have some pipe async like (myObservable$ | async)?.a so I want to keep my object as is and only concatenate my items inside this object, but the scan operator maps my object to the new array (I totally understand it is the normal behavior).

So how can I concatenate my arrays in my object without this mapping?

Example:

What I have:

{
  a: 'first',
  b: 'first',
  items: [{
    c: 'bla',
    d: 'bla'
  }, {
    c: 'blabla',
    d: 'blabla'
  }]
}

and

{
  a: 'second',
  b: 'second',
  items: [{
    c: 'second bla',
    d: 'second bla'
  }]
}

What I want:

{
  a: 'second',
  b: 'second',
  items: [{
    c: 'bla',
    d: 'bla'
  }, {
    c: 'blabla',
    d: 'blabla'
  }, {
    c: 'second bla',
    d: 'second bla'
  }]
}

Upvotes: 0

Views: 912

Answers (3)

frido
frido

Reputation: 14109

Concatenate the current items to the accumulated items and assign them to your current items.
Return the current object.

scan((acc: any, curr: any) => (curr.items = acc.items.concat(curr.items), curr))

Or without mutating objects

scan((acc: any, curr: any) => ({ ...curr, items: [ ...acc.items, ...curr.items ] }))

Upvotes: 1

Vivek Jain
Vivek Jain

Reputation: 2864

Try this.

var object1 = {
  a: 'first',
  b: 'first',
  items: [{
    c: 'bla',
    d: 'bla'
  }, {
    c: 'blabla',
    d: 'blabla'
  }]
};

var object2 = {
  a: 'second',
  b: 'second',
  items: [{
    c: 'second bla',
    d: 'second bla'
  }]
};


object2.items = [...object1.items, ...object2.items]
console.log(object2);

Upvotes: 0

ng-hobby
ng-hobby

Reputation: 2199

Try this:

object.items = [ ...object.items, ...new ]

Upvotes: 0

Related Questions