Reputation: 563
I have an object with these properties :
{
title: 'Test',
places: [
{
id: 1,
longitude: 48.8469511,
latitute: 2.3077989,
address: 'Pont de Bir-Hakeim',
city: {name: 'Paris', id: 1}
},
{
id: 2,
longitude: 48.855225,
latitute: 2.288048,
address: 'Palais-Musée Galliera, 10 avenue Pierre-1er-de-Serbie',
city: {name: 'Paris', id: 1}
},
{
id: 3,
longitude: 50.8283315,
latitute: -115.2608429,
address: 'Fortress Moutain',
city: {name: 'Calgary', id: 2}
}
]
}
Here is the result I want :
[
{
id: 1,
name: 'Paris'
},
{
id: 2,
name: 'Calgary'
},
]
How can I achieve that by using groupBy
map
reduce
?
Here is what I tried :
return from(movie.places).pipe(
groupBy(place => place.city.name),
mergeMap(place => place.pipe(map(obj => obj.city.name))),
toArray()
);
Which produce :
['Paris', 'Paris', 'Calgary']
It's not very clear in my head on how to use groupBy
, map
, mergeMap
, toArray
together...
Thanks for the help!
Upvotes: 1
Views: 995
Reputation: 9638
In one line, I think, and just using toArray, map, distinct
operators you can do:
return from(movie.places).pipe(map(place => place.city), distinct(entry => entry.id),toArray());
Upvotes: 0
Reputation: 7875
you can do something like this :
source$.pipe(
map(state => state.places), // transform your source object to list of places.
// Transform your list of place by list of city, then reduce it for unduplicate it.
map(state => state.map(e => e.city).reduce( ( acc, cur ) => [
...acc.filter( ( obj ) => obj.id !== cur.id ), cur
], [] ))
).subscribe(console.log);
i have split in two different map to keep clear my code, you can easily merge it to single map if you prefer.
this code is also not safe for very large collection of data, prefer normalizr approch if you want to efficiently deal with larg data.
source for uniq array of object base from id
Upvotes: 1