Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  12] [ 6]  / answers: 1 / hits: 18194  / 6 Years ago, tue, september 4, 2018, 12:00:00

My service called getList returns a list of items.
I want to loop through the list of items and format the date.
Then return the formatted array.



My current attempt doesnt return the items in the array because I use flatMap in order to loop the items in map.



I'm using angular6 and rxjs.



My attempt:



this.list$ = this.service.getList()
.pipe(
flatMap(response => response.items),
map(item => {
item.date = moment(item.date).format('YYYY-MM-DD').toString();
return item;
})
);

More From » angular

 Answers
16

You can simply add toArray() at the end of your pipe



this.list$ = this.service.getList()
.pipe(
mergeMap(response => response.items),
map(item => {
item.date = moment(item.date).format('YYYY-MM-DD').toString();
return item;
}),
toArray()
)


What is probably better though is to restructure a bit your code, use the Observable map operator instead of flatMap (a.k.a. mergeMap) and inside it use the Array map method to do the formatting. In other words something like



pipe(
map(response => response.items.map(item => {
item.date = moment(item.date).format('YYYY-MM-DD').toString();
return item;
}))
)


The second approach avoids the unfolding of the Array (which in the first solution you do using flatMap) and the subsequent recreation of the Array, or at least confines this logic into the map method of Array


[#53563] Friday, August 31, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;