RxJS5 - Operator to convert object map to array

早过忘川 提交于 2019-12-10 13:34:14

问题


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.

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)

Data:

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

Current:

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

Possible?

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

回答1:


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/rxjs@5.0.3/dist/global/Rx.min.js"></script>


来源:https://stackoverflow.com/questions/41865471/rxjs5-operator-to-convert-object-map-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!