Reputation: 5761
I have the following code which works but I was looking for a cleaner solution:
const routeLists = solution.vehicle_list[0].route_list
const solutionMarkers = routeLists.map((el: any) => (
{
latitude: el.source_latitude,
longitude: el.source_longitude,
type: el.route_type
}
))
const customerMarkers = routeLists.map((el: any) => {
return el.destinations_list.map((el: any) => {
return {
latitude: el.latitude,
longitude: el.longitude,
type: 'customer'
}
})
}).map((el: MarkerType, i: number) => el[i])
const markers = [...solutionMarkers, ...customerMarkers]
route_list sample data:
...
"route_list": [
{
"route_id": "dc Truck 231 Route #1",
"route_type": "dc",
"sequence_number": 0,
"source_id": 0,
"source_latitude": 33.87,
"source_longitude": -123.87,
"planned_start": "2012-04-23T18:25:43.511Z",
"planned_end": "2012-04-23T18:25:43.511Z",
"activity_list": [
{
"sequence_number": 0,
"type": "loading",
"planned_start": "2012-04-23T18:25:43.511Z",
"planned_end": "2012-04-23T18:25:43.511Z",
"planned_duration": 0
}
],
"destinations_list": [
{
"destination_id": 0,
"sequence_number": 0,
"address": "string",
"latitude": 33.87,
"longitude": -118.34,
"planned_arrival": "2012-04-23T18:25:43.511Z",
"order_id": 0,
"time_window_start": "2012-04-23T18:25:43.511Z",
"time_window_end": "2012-04-23T18:25:43.511Z"
}
]
}
]
...
is there a way to map on routeLists
only once? I have tried to use concat within customerMarkers but I didn't make it to work yet
Upvotes: 1
Views: 67
Reputation: 1242
You can use reduce, like this:
const markers = routeLists.reduce((acc, rec) => {
let result = [{
latitude: rec.source_latitude,
longitude: rec.source_longitude,
type: rec.route_type
}]
if (typeof rec.destinations_list !== 'undefined' && rec.destinations_list.length) {
return [...acc, ...result, ...(rec.destinations_list.map((el: any) => {
return {
latitude: el.latitude,
longitude: el.longitude,
type: 'customer'
}
}))]
}
return [...acc, ...result]
}, [])
Upvotes: 2
Reputation: 2704
You can use reduce then nest destinations list in it:
const markers = routeLists.reduce((accum, current) => {
accum.push({
latitude: current.source_latitude,
longitude: current.source_longitude,
type: current.route_type
});
current.destinations_list.forEach(el => {
accum.push({
latitude: el.latitude,
longitude: el.longitude,
type: "customer"
});
});
return accum;
}, []);
Upvotes: 1