Basics
To create a copy of an immutable object in JavaScript, you can use the Object.assign()
method or the spread operator (...
). These methods allow you to create a new object with the properties of the original object and then modify the new object as needed.
For example:
const person = {
name: 'John',
age: 30
};
// Using Object.assign()
const personCopy1 = Object.assign({}, person, { name: 'Jane' });
// Using the spread operator
const personCopy2 = { ...person, name: 'Jane' };
console.log(personCopy1); // { name: 'Jane', age: 30 }
console.log(personCopy2); // { name: 'Jane', age: 30 }
To update an immutable object, you can create a copy of the object with the desired changes, and then use Object.freeze()
or Object.seal()
to prevent the object from being modified further.
For example:
const person = {
name: 'John',
age: 30
};
const updatedPerson = Object.freeze({ ...person, age: 31 });
console.log(updatedPerson); // { name: 'John', age: 31 }
To delete a property from an immutable object, you can create a copy of the object with the desired property removed.
For example:
const person = {
name: 'John',
age: 30,
address: '123 Main St'
};
const updatedPerson = Object.freeze({
...person,
address: undefined
});
console.log(updatedPerson); // { name: 'John', age: 30 }
It's also possible to use a library like Immutable.js, which provides methods for creating, updating, and deleting properties on immutable objects.
Last updated