How to change a property on an object without mutating it?

Two ways...

  1. You can use Object.assign:

    const a = { x: "Hi", y: "Test" }
    const b = Object.assign({}, a, { x: "Bye" });
    console.log("a:", a);
    console.log("b:", b);
    console.log("a === b:", a === b);
  2. Or you can use the object spread operator.

    The spread operator allows you to "assign" all properties of one object to another.

    We can use it here within an object literal to assign all properties of a to b:

    const additions = { x: "Bye" }
    const a = { x: "Hi", y: "Test" }
    const b = { ...a,  ...additions } // or { ...a, x: "Bye" }
    console.log("a:", a);
    console.log("b:", b);
    console.log("a === b:", a === b);

there's an easy way to change object property without mutating the original object.

const a = {x: "Hi", y: "Test"};
const b = {...a, y: "hello"}; 

Tags:

Javascript