-3

In my react app, I currently have two arrays with objects that I would like to combine.

  const cars = [ 
    {'car': 'porsche', 'description': 'luxury', 'driverId': 4},
    {'car': 'ferrari', 'description': 'beatiful', 'driverId': 2},
    {'car': 'bmw', 'description': 'slow', 'driverId': 5} 
    ]

  const drivers = [
    {'driver':{'car': 'kia', 'name':'John' , 'description': 'Overweight'}},
    {'driver':{'car': 'toyota', 'name':'Koko' , 'description': 'Ugly looking'}},
    {'driver':{'car': 'nissan', 'name':'Goku' , 'description': 'Tall'}}
    ]

After combining two objects, I would like end result to be like this.

   const carInfo = [
    {'car': 'porsche', 'description': 'luxury', 'driverId': 4, 'carName':'kia', 'name':'John' , 'descriptionDriver': 'Overweight'},
    {'car': 'ferrari', 'description': 'beatiful', 'driverId': 2, 'carName': 'toyota', 'name':'Koko' , 'descriptionDriver': 'Ugly looking'},
    {'car': 'bmw', 'description': 'slow', 'driverId': 5, 'carName': 'nissan', 'name':'Goku' , 'descriptionDriver': 'Tall'}
    ]

Basically, I would like to change the key name in drivers object then combine them. Because spread operator wouldn't work when there are same key name between objects. How can I get this result?

Phil
  • 157,677
  • 23
  • 242
  • 245
Judoboy Alex
  • 326
  • 1
  • 14
  • Are the two arrays always guaranteed to be the same length? What should happen if they're not? – Phil Oct 18 '20 at 22:23
  • 1
    Why not just insert each `driver` object under the key `driver`? Then you don't need to worry about conflicting object keys – Phil Oct 18 '20 at 22:25

1 Answers1

3

Of course you can use spread operator, just map over it and "rename" some props:

drivers.map(x => x.driver).map((x, i) => {
  let { car, description, ...rest } = x
  return { ...rest, carName: car, descriptionDriver: description, ...cars[i] }
})
siaznik
  • 496
  • 2
  • 5