javascript - 将 Array 序列化为元素,使用 RxJS 进行转换,并将元素组装回数组

标签 javascript arrays angular rxjs rxjs5

在 Angular2 中,我有很多 Observable<any[]> (发出数组的 Observable)在 http.get() 中产生的后代或通过 websocket 操作提供,因此不 .complete() 但随着时间的推移发出多个值。

我经常需要使用 RxJS 运算符转换数组中的元素(我不想使用 Array.prototype.* 转换!)并将单个元素组装回数组,作为单个实体发出。

但我不知道如何将元素组装回数组。

例子:

const n$ = new Subject();

const output = n$
    // create an observable emitting the individual elements
    // of the array
    .mergeMap(n => n)

    // some kind of transform on the elements
    .distinct((n1, n2) => n1 == n2)
    .map(n => n*n)

    // how to assemble back to an array here???
    // not working:
    // .buffer(n$)
    // also not working (subject does not complete!)
    // .toArray()

output.subscribe(v => console.log(v))

n$.next([1,1,1,2,3]);
n$.next([4,5,5,6]);

// Wanted output:
// [1, 4, 9]
// [16, 25, 36]

最佳答案

如果您有多个值并想要一个值(数组), reduce toArray应该是你所追求的:

Rx.Observable.from([0, 1, 1, 2, 3])
    .distinct()
    .map((n) => n * n)
    // .reduce((acc, n) => { acc.push(n); return acc; }, [])
    .toArray()
    .subscribe((a) => { console.log(a); })

如果你有一个 Observable<any[]> , 只需将其放入 mergeMap :

const output = n$
    .mergeMap((a) => Rx.Observable.from(a)
        .distinct()
        .map((n) => n * n)
        // .reduce((acc, n) => { acc.push(n); return acc; }, [])
        .toArray()
    )
    .subscribe(a => { console.log(a); });

关于javascript - 将 Array 序列化为元素,使用 RxJS 进行转换,并将元素组装回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989389/

相关文章:

php - 不掉落在其他拖动上

arrays - 从 postgres 表中提取 json 数组给出错误 : cannot extract elements from a scalar

javascript - 在 ngOnDestroy() 上打开模态并且不重定向到上一页

删除对象数组时出现 C++ 堆异常

angularjs - 每当添加新行时,如何在 ng2-smart-table 中使用 post 方法?

javascript - 数据显示正确,但控制台显示 "Cannot read property ' map '未定义”

javascript - 找不到模块 : Can't resolve 'material-ui/styles/colors'

javascript - 数组过滤器和数组显示

javascript - Webdriver.IO 接收到 : "npm ERR! Test failed. See above for more details." but can't see the errors

php - 在 Twig 中获取数组键? (交响乐)