Issue
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();
Solution
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>
Answered By - cpt_redbeard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.