0

I'm trying to conditionally merge data from two http request together into a single object. Please consider these objects.

vehicles: [
{
  vId: 1,
  color: 'green',
  passengers: [
    {
      name: 'Joe',
      age: 22
    },
    {
      name: 'Jack',
      age: 32
    }
  ]
}
more vehicles....]



pDetails: [
  {
    vId: 1,
    detail: tall
  },
  {
    vId: 1,
    detail: 'fat'
  },
  { 
    vId 2,
    detail: 'sad'
  } more details.....
]

Where the vIds match between two objects I want to push the pDetails object into a new array in the matching object in the vehicles array. I'm using Angular 5, TS and have added Lodash to my project. I'm getting hung up on how to iterate through nested arrays. I'm new to JS an not yet very familiar with the apis. Is there something in TS, ES6, Angular, or Lodash that might make this easier?

Here's the closest I've gotten so far:

this.getVehicles().subscribe(
      data => { v = data.result.objects },
      err => console.error(err),
      () => Object.keys(v).forEach(key => {
      console.log(v[key]); //mapping logic here
    })

This successfully iterates through the vehicles array but what I think I want to do is integrate though each v.passenger object and for each do a search on the pDetails array, copy matches, push to a temp array and then assign to v.passengers. I'm still having trouble figuring out how to iterate each vehicle's passenger array.

rennyB
  • 143
  • 3
  • 10

1 Answers1

0

Using the rxjs functions would help you in this kind of concerns.

Here is code suggestion to get vehicules with detail using combineLatest (code for demonstration, not tested) :

// The first observable pushed value would be
// and array of the pushed values by the Observables
combineLatest(this.getVehiclesDetails(),this.getVehicles())
.pipe(
    // Using the returned values, you could transform them to what you want
    map(([vehicules, details]) =>
        // Here we transform our vehicules array to vehiculesWithDetail array
        vehicules.map(vehicule => {
            // We get the detail for the processed vehicule
            const detail = details.find(d => d.vdId == vehicule.vdId);
            // We merge the two objects in one
            return Object.Assign(vehicule, detail);
        })
    )
)
ibenjelloun
  • 7,425
  • 2
  • 29
  • 53