8

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();
luiscla27
  • 4,956
  • 37
  • 49
Thibs
  • 8,058
  • 13
  • 54
  • 85
  • You could use Angular in-built `filter` for this. Then you need import lodash only once into where your filter is defined. https://docs.angularjs.org/guide/filter – aarosil Jan 26 '17 at 03:47

1 Answers1

17

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>
cartant
  • 57,105
  • 17
  • 163
  • 197
cpt_redbeard
  • 215
  • 3
  • 6
  • That won't necessarily output an array with the elements in the correct order. – cartant Jan 26 '17 at 04:39
  • Did I miss where the op wanted the array in a specific order? The reason I answered similar but different is for that exact reason. No need to code for specs that just aren't there. – cpt_redbeard Jan 26 '17 at 13:55
  • 1
    I did not need the array in order and this is a good alternative, which is what I was asking for. Thank-you – Thibs Jan 26 '17 at 15:27
  • Keeping the order of the attributes is tricky, basically, the only guaranteed way of doing it is to define a different array with the expected order and then reorder your result, read more [here](https://stackoverflow.com/a/38218582/1657465) – luiscla27 Nov 24 '21 at 01:16