galaxyfreak
galaxyfreak

Reputation: 79

Combining two API responses into one object without map/loop

I'm in a situation where I have to cover for poor API entity associations on the client:

Simplified example would be:

/api/cars

[
  {
    "carId": 1,
    "name": "BMW"
  },
  {
    "carId": 2,
    "name": "Citroen"
  }
]

/api/carcolors

[
  {
    "color": "blue",
    "carId": 1
  },
  {
    "color": "red",
    "carId": 2
  }
]

And I would need to get a data object like

class Car {
    String id;
    String name;
    String color;
}

Does anybody know a better way to handle this than calling /cars, which creates list of Car objects with color null, then doing request /carcolors, getting CarColor objects and then map/loop to put color to a car model.

Upvotes: 0

Views: 668

Answers (1)

trincot
trincot

Reputation: 350961

You will have to loop, but you can avoid a nested loop with the use of a temporary Map, keyed by carId:

let cars = [{"carId": 1,"name": "BMW"},{"carId": 2,"name": "Citroen"}]
let colors = [{"color": "blue","carId": 1},{"color": "red","carId": 2}]

let carmap = new Map(cars.map(car => [car.carId, {...car}]));
colors.forEach(color => Object.assign(carmap.get(color.carId), color));
let result = Array.from(carmap.values())

console.log(result);

Upvotes: 0

Related Questions