Copying an object by value in JavaScript means creating a completely new object that has the same values as the original object, but is independent of it. This means changes to the copy won't affect the original object, and vice versa. Here are the common methods:
1. Using the Spread Syntax
The spread syntax (...
) allows you to expand an iterable into its individual elements. You can use it to create a new object with the same properties and values as the original:
const originalObject = { name: 'John', age: 30 };
const copiedObject = { ...originalObject };
copiedObject.name = 'Jane';
console.log(originalObject); // Output: { name: 'John', age: 30 }
console.log(copiedObject); // Output: { name: 'Jane', age: 30 }
2. Using Object.assign()
The Object.assign()
method copies the values of all enumerable own properties from one or more source objects to a target object.
const originalObject = { name: 'John', age: 30 };
const copiedObject = Object.assign({}, originalObject);
copiedObject.age = 35;
console.log(originalObject); // Output: { name: 'John', age: 30 }
console.log(copiedObject); // Output: { name: 'John', age: 35 }
3. Using JSON.parse()
and JSON.stringify()
This method serializes the original object into a JSON string and then parses it back into a new object:
const originalObject = { name: 'John', age: 30 };
const copiedObject = JSON.parse(JSON.stringify(originalObject));
copiedObject.name = 'Jane';
console.log(originalObject); // Output: { name: 'John', age: 30 }
console.log(copiedObject); // Output: { name: 'Jane', age: 30 }
4. Using Object.entries()
and Object.fromEntries()
This method iterates through the original object's key-value pairs and creates a new object with the same properties and values:
const originalObject = { name: 'John', age: 30 };
const copiedObject = Object.fromEntries(Object.entries(originalObject));
copiedObject.name = 'Jane';
console.log(originalObject); // Output: { name: 'John', age: 30 }
console.log(copiedObject); // Output: { name: 'Jane', age: 30 }
Remember that these methods only create a shallow copy. If your original object contains nested objects, you'll need to use a recursive approach or a dedicated library to copy them by value as well.