【问题标题】:Concatenate previous and new value of arrays inside an object in an Observable在 Observable 中连接对象内的数组的先前值和新值
【发布时间】:2020-08-19 11:51:03
【问题描述】:

我有一个对象,其中包含一组项目,如下所示:{ a: string, b: string, items: Something[] }。 在我的 observable 中,当发出一个新值时,我希望将项目的先前值与新值连接起来,所以我使用了scan operator。它的作用类似于myObservable$.pipe(scan((acc: any, curr: any) => [...acc.items, ...curr.items]))

它按预期工作,但是我有一些像(myObservable$ | async)?.a 这样的管道异步,所以我想保持我的对象不变,并且只在这个对象中连接我的项目,但是扫描运算符将我的对象映射到新数组(我完全理解这是正常行为)。

那么如何在没有此映射的情况下连接对象中的数组?

例子:

我有什么:

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

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

我想要什么:

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

【问题讨论】:

  • 你能用一个例子清楚地解释你有什么和你想要什么吗?
  • 我刚刚编辑了答案!

标签: angular rxjs


【解决方案1】:

将当前项目连接到累积项目并将它们分配给您当前的项目。
返回当前对象。

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

或者不改变对象

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      试试这个。

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

      【讨论】:

        猜你喜欢
        • 2022-11-30
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 2017-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        相关资源
        最近更新 更多