【问题标题】:Scan a stream of objects and add a property with the running sum in RxJS扫描对象流并在 RxJS 中添加具有运行总和的属性
【发布时间】:2021-10-13 05:26:28
【问题描述】:

假设我有如下对象的源流:

source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}])

在派生的 observable 中,我想维护一个额外的属性,其中包含成本的运行总和

// Expected derived stream
{ id: 1, cost: 10, totalCost: 10}
{ id: 2, cost: 5,  totalCost: 15}
{ id: 3, cost: 3,  totalCost: 18}
{ id: 4, cost: 10, totalCost: 28}

用rxjs怎么实现?

【问题讨论】:

    标签: javascript rxjs


    【解决方案1】:

    我设法找到了这个解决方案:

    import { from } from "rxjs";
    import {scan} from "rxjs/internal/operators";
    
    let source$ = from([{ id: 1, cost: 10},{ id: 2, cost: 5},{ id: 3, cost: 3},{ id: 4, cost: 10}]);
    
    
    source$
    .pipe(
      scan((acc,curr) => {
          return {...curr, totalCost: acc.totalCost + curr.cost}
      }, {totalCost:0})
    ) 
    .subscribe(console.log)
    
    

    https://codesandbox.io/s/rxjs-playground-forked-3bdpd

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2017-04-15
      • 1970-01-01
      • 2015-12-16
      • 2020-09-26
      • 2011-12-10
      相关资源
      最近更新 更多