JavaScript > Objects and Arrays > Object Basics > Object methods

JavaScript Object.assign(): Merging Objects

This guide demonstrates how to use Object.assign() in JavaScript to merge objects, copy properties, and create new objects with combined properties. Learn how to handle shallow copies and default values.

Basic Usage of `Object.assign()`

Object.assign(target, ...sources) copies the values of all enumerable own properties from one or more source objects to a target object. It returns the modified target object. If properties in the source objects have the same keys, the values from the later source objects will overwrite the earlier ones. It is important to note that Object.assign performs a shallow copy.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target); // Output: { a: 1, b: 4, c: 5 }
console.log(returnedTarget); // Output: { a: 1, b: 4, c: 5 }
console.log(target === returnedTarget); // Output: true

Shallow Copy Explained

Object.assign performs a shallow copy, meaning that if a property value is an object itself, only the reference to the object is copied. Changes to nested objects in the target will affect the source if they point to the same nested object in memory.

const target = { a: { value: 1 } };
const source = { a: { value: 2 } };

const returnedTarget = Object.assign(target, source);

console.log(target); // Output: { a: { value: 2 } }
console.log(returnedTarget); // Output: { a: { value: 2 } }

target.a.value = 3;

console.log(source.a.value); // Output: 2
console.log(returnedTarget.a.value); // Output: 3

Creating a New Object

To avoid modifying the original target object, you can create a new object as the target by passing an empty object {} as the first argument to Object.assign().

const source = { a: 1, b: 2 };

const newObject = Object.assign({}, source);

console.log(newObject); // Output: { a: 1, b: 2 }
console.log(source === newObject); // Output: false

Merging Multiple Objects

Object.assign() can merge multiple source objects into a single target object. The properties from later source objects will overwrite properties with the same keys in earlier source objects.

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const obj3 = { c: 3 };

const mergedObject = Object.assign({}, obj1, obj2, obj3);

console.log(mergedObject); // Output: { a: 1, b: 2, c: 3 }

Concepts Behind the Snippet

Object.assign() is used to copy the values and properties from one or more source objects to a target object. The method is often used when you need to create a new object with properties from multiple existing objects.

Real-Life Use Case

Consider a scenario where you're managing user profiles with default settings. You can use Object.assign() to merge the default settings with user-specific preferences, creating a customized profile object without directly modifying either the default settings or the user preferences.

Best Practices

  • Use Object.assign() to merge objects immutably by passing an empty object as the target.
  • Be aware of the shallow copy behavior and consider deep cloning for nested objects if necessary.
  • Avoid modifying the original objects when merging them.

Interview Tip

Be prepared to explain how Object.assign() works, its shallow copy behavior, and how to use it to merge objects immutably. Understand the difference between shallow and deep copies.

When to Use Them

  • Use when you need to merge properties from multiple objects into a single object.
  • Use when you need to create a new object by combining properties from existing objects.

Memory Footprint

Object.assign() creates new object references when copying primitive values. For nested objects, it only copies the reference, which means modifications affect both the original and copied objects. Be mindful of this shallow copy behavior.

Alternatives

  • Spread syntax (...) provides a more concise way to merge objects.
  • Deep cloning libraries like Lodash's _.cloneDeep() can be used for deep copies to avoid shallow copy issues.

Pros of using Object.assign

  • Simple and easy to use for merging objects.
  • Supports merging multiple objects at once.
  • Can be used to create new objects without modifying the original ones.

Cons of using Object.assign

  • Performs a shallow copy, which can lead to unintended modifications of nested objects.
  • Does not handle properties with null or undefined values gracefully.
  • Not suitable for deep cloning nested objects.

FAQ

  • What happens if the source and target objects have properties with the same name?

    The properties from the later source objects will overwrite properties with the same name in the earlier source objects or the target object.
  • How do I avoid modifying the original objects when merging them with Object.assign()?

    Pass an empty object {} as the first argument to Object.assign(). This creates a new object with the merged properties without modifying the original objects.
  • How can I perform a deep copy instead of a shallow copy with Object.assign()?

    For deep copying, you can use libraries like Lodash (_.cloneDeep()) or implement a custom deep copy function.