本文介绍了RxJS5-将对象映射转换为数组的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回对象映射的服务,该对象映射随后在仅包含数组的Angular ngFor中使用.因此,我将地图运算符与lodash的_toArray一起使用,以将数据转换为数组.

I have a service that returns an object map which is then used in Angular's ngFor which only takes arrays. So, I am using the map operator with lodash's _toArray to convert the data to an array.

尽管这行得通,但是我必须在需要执行此操作的所有位置导入lodash,而且它似乎很脆弱.我本来打算创建一个自定义运算符,但是也许已经有一个运算符已经做到了?我似乎找不到合适的人

Although this works, I then have to import lodash everywhere I need to do this and it seems brittle. I was going to look into creating a custom operator, but perhaps there is an operator that already does this? I can't seem to find the right one(s)

数据:

{ 0 : {data : 'lorem'}, 1 : {data : 'lorem'}, 2 : {data : 'lorem'} }

当前:

this.http
    .get('/api')
    .map(data => _.toArray(data));

可能吗?

this.http
    .get('/api')
    .mapToArray();

推荐答案

您应该能够使用RxJS的map运算符以及仅使用Object.keys()方法来执行所需的操作.

You should be able to do what you want with RxJS's map operator and just the Object.keys() method.

Rx.Observable
  .of({
    0: { data : 'lorem' },
    1: { data : 'lorem' },
    2: { data : 'lorem' }
  })
  .map(data => Object.keys(data).map(k => data[k]))
  .subscribe(data => console.log(data));
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.min.js"></script>

这篇关于RxJS5-将对象映射转换为数组的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:36