DEV Community

Khafido Ilzam
Khafido Ilzam

Posted on

How to Clone Object Properly?

You can clone the properties of an object using the Object. assign() method and the spread operator. With these, you can change the properties of the cloned object without changing the properties of the object from which it was cloned.

Clone Object Properly

How the Object.assign() method Works

The object.assign() method copies properties from an object (the source) into another object (the target) and returns the modified target object.

Here's the syntax:
Object.assign(target, source)

const staff = {
    name: "Strengthened",
    age: 43,
    hobbies: ["reading", "Swimming"]
}

const staff2 = Object.assign({}, staff);
staff2.age = 53;

console.log(staff.age); // 43
console.log(staff2.age); // 53
Enter fullscreen mode Exit fullscreen mode

How the Spread Operator Works

Here's the syntax of the spread operator:
const newObj = {...obj}

Using the spread operator is quite simple. You need to place three dots ... before the name of the object whose properties you intend to clone:

const staff = {
    name: "Strengthened",
    age: 43,
    hobbies: ["reading", "Swimming"]
}

const staff2 = { ...staff };
staff2.age = 53;

console.log(staff.age); // 43
console.log(staff2.age); // 53
Enter fullscreen mode Exit fullscreen mode

Top comments (0)