Wednesday, February 19, 2025

JavaScript, How can we create a copy of Object Literal?

How can we create a copy of Object Literal?


In JavaScript, there are multiple ways to create a copy of an object literal. A copy can be either shallow or deep.

Shallow Copy: Duplicates only the top-level properties. If the object contains nested objects, the inner objects are still referenced (not duplicated).
Deep Copy: Duplicates the object and all nested objects, making an independent copy that doesn’t share references with the original.
Let's explore different methods for each type:

1. Shallow Copy Methods
Method 1: Using Object.assign()
Object.assign() is a method for creating a shallow copy of an object.



const original = { name: "Alice", age: 30 };
const copy = Object.assign({}, original);

copy.name = "Bob";
console.log(original.name); // "Alice" - original is not affected
console.log(copy.name); // "Bob"
Method 2: Using the Spread Operator {...}
The spread operator (...) creates a shallow copy of an object and is often simpler than Object.assign().



const original = { name: "Alice", age: 30 };
const copy = { ...original };

copy.age = 25;
console.log(original.age); // 30 - original is not affected
console.log(copy.age); // 25
2. Deep Copy Methods
For deep copies, we need methods that copy nested objects as well.

Method 1: Using JSON.parse(JSON.stringify())
A common way to create a deep copy is to convert the object to a JSON string and then parse it back into an object. However, this method has limitations (e.g., it won’t handle functions, undefined, Date, or special values like Infinity).



const original = { name: "Alice", age: 30, address: { city: "New York" } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.address.city = "San Francisco";
console.log(original.address.city); // "New York" - original is not affected
console.log(deepCopy.address.city); // "San Francisco"
Method 2: Using a Recursive Function
For complex objects with nested properties, a recursive function can be used to create a true deep copy.



function deepClone(obj) {
    if (obj === null || typeof obj !== "object") return obj;

    const copy = Array.isArray(obj) ? [] : {};

    for (const key in obj) {
        copy[key] = deepClone(obj[key]);
    }

    return copy;
}

const original = { name: "Alice", age: 30, address: { city: "New York" } };
const deepCopy = deepClone(original);

deepCopy.address.city = "San Francisco";
console.log(original.address.city); // "New York" - original is not affected
console.log(deepCopy.address.city); // "San Francisco"
Summary
Use Object.assign() or spread operator {...} for shallow copies.
Use JSON.parse(JSON.stringify()) for simple deep copies.
Use a recursive function for a more robust deep copy, especially with nested structures.

No comments:

Post a Comment

Hot Topics