How can I add or remove object properties without mutating the original?
Quick answer
For a simple JavaScript object, make a new object with { ...original, active: true } to add or replace a property. To omit a property, use const { secret, ...publicData } = original. Both create a new outer object instead of changing original. These are shallow operations: nested object values are still shared references, so changing a nested value through the copy can affect the original. [S1]
The question, the details, the next step.
A practical checklist
Use
{ ...original, key: value }to add or override a top-level property in a new object.Use
const { key, ...copy } = originalto omit a named property from a new object.Inspect both the original and the copy to confirm the intended top-level results.
Check whether nested objects or arrays are shared before changing nested values.
Remember that omitting a property from a copy does not delete it from the original.
A few more useful answers
Does object spread change the original object?
No. In an object literal, { ...original } creates a new outer object, and adding a later property changes that new object rather than the original. [S1]
Will the copy include the original object's prototype and non-enumerable properties?
No. Object-literal spread copies enumerable own properties; it does not copy non-enumerable properties or the prototype. [S1]
What if I want to omit more than one property?
Destructure each property you want to leave out, then collect the rest. For example: const { secret, token, ...publicData } = original;
Sources
References used for this guide.
- [S1] Spread syntax (...) — JavaScript | MDN developer.mozilla.org · Checked
