In JavaScript, there are several ways to create a copy of an object, each with its own advantages and disadvantages.
Object.assign()
Object.assign() is a method that copies the values of all enumerable own properties from one or more source objects to a target object. Here’s an example:
const obj1 = { foo: "bar", baz: "qux" };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // Outputs { foo: "bar", baz: "qux" }
In this example, Object.assign() creates a new object () and copies the properties of obj1 to it. This creates a shallow copy of obj1.
Spread operator
The spread operator (...) can also be used to create a copy of an object. Here’s an example:
const obj1 = { foo: "bar", baz: "qux" };
const obj2 = { ...obj1 };
console.log(obj2); // Outputs { foo: "bar", baz: "qux" }
In this example, the spread operator creates a new object and copies the properties of obj1 to it. This also creates a shallow copy of obj1.
JSON.parse() and JSON.stringify()
You can also create a copy of an object by converting it to a JSON string using JSON.stringify(), and then converting the JSON string back to an object using JSON.parse(). Here’s an example:
const obj1 = { foo: "bar", baz: "qux" };
const obj2 = JSON.parse(JSON.stringify(obj1));
console.log(obj2); // Outputs { foo: "bar", baz: "qux" }
In this example, JSON.stringify() converts obj1 to a JSON string (’"foo":"bar","baz":"qux"’), and then JSON.parse() converts the JSON string back to an object. This creates a deep copy of obj1, because all nested objects and arrays are also copied.
Object.create()
Object.create() is a method that creates a new object with the specified prototype object and properties. Here’s an example:
const obj1 = { foo: "bar", baz: "qux" };
const obj2 = Object.create(obj1);
console.log(obj2); // Outputs {}
console.log(obj2.foo); // Outputs "bar"
console.log(obj2.baz); // Outputs "qux"
In this example, Object.create() creates a new object () with obj1 as its prototype object. This creates a new object that inherits the properties of obj1, but doesn’t create a copy of obj1 itself.
In summary, there are several ways to create a copy of an object in JavaScript, each with its own advantages and disadvantages. Object.assign() and the spread operator create shallow copies of objects, while JSON.parse() and JSON.stringify() create deep copies of objects. Object.create() creates a new object with a specified prototype object. The choice of which method to use depends on the specific use case and requirements of the application.