Combining Objects in JavaScript using Spread Operator
In JavaScript, the spread operator (...
) offers a convenient way to merge objects. The spread operator can be used to combine objects and modify existing objects efficiently. Let's dive into the code snippet:
// Spread in JS helps to combine two objects
const car = {
wheels: 4,
emoji: '🚗',
doors: 4
}
var Ferrari = {
emoji: '🏎️',
doors: 2,
maker: 'Ferrari'
}
// Since both object has different values for door, the last object (Ferrari) takes precedence
var newCar = Object.assign({}, car, Ferrari)
Console.log(newCar) //{ wheels: 4, emoji: '🏎️', doors: 2, maker: 'Ferrari' }
// or
newCar = {...car, ...Ferrari}
console.log(newCar) //{ wheels: 4, emoji: '🏎️', doors: 2, maker: 'Ferrari' }
// or
Ferrari = {
...car,
emoji: '🏎️',
doors: 2,
maker: 'Ferrari'
}
console.log(Ferrari) // { wheels: 4, emoji: '🏎️', doors: 2, maker: 'Ferrari' }
// When Car takes precedence
Ferrari = {
emoji: '🏎️',
doors: 2,
maker: 'Ferrari',
...car,
}
console.log(Ferrari) //{ emoji: '🚗', doors: 4, maker: 'Ferrari', wheels: 4 }