Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS5 - Operator to convert object map to array

Tags:

angular

rxjs5

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();
like image 899
Thibs Avatar asked Jan 26 '17 03:01

Thibs


1 Answers

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>
like image 88
cpt_redbeard Avatar answered Oct 01 '22 19:10

cpt_redbeard