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();
1
  • You could use Angular in-built filter for this. Then you need import lodash only once into where your filter is defined. docs.angularjs.org/guide/filter Commented Jan 26, 2017 at 3:47

1 Answer 1

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/[email protected]/dist/global/Rx.min.js"></script>

Sign up to request clarification or add additional context in comments.

4 Comments

That won't necessarily output an array with the elements in the correct order.
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.
I did not need the array in order and this is a good alternative, which is what I was asking for. Thank-you
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.