Spread Syntax
JavaScript provides a highly efficient “spread syntax” (...) for moving groups of properties out of an object. It is the preferred way to shallow-copy objects and merge multiple objects together.
Merging Objects
You can spread the properties of existing objects into a brand new object literal.
const engineering = {
lane: "grand magus",
hunter: "software engineer"
};
const video = {
stass: "video producer"
};
// Merge both objects into a single new one
const allEmployees = { ...engineering, ...video };
console.log(allEmployees);
/* Output:
{
lane: "grand magus",
hunter: "software engineer",
stass: "video producer"
}
*/
Handling Collisions
When merging objects, if two properties share the exact same key, the property from the object that was spread last (the right-most object) will overwrite the previous ones.
const engineering = {
lane: "software engineer", // This will be overwritten
hunter: "software engineer",
};
const video = {
lane: "cringe youtuber", // This takes priority
alex: "video producer",
};
const merged = { ...engineering, ...video };
console.log(merged.lane);
// Output: "cringe youtuber"