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

后端 未结 5 2155
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 00:40
const a = {x: "Hi", y: "Test"}
const b = ???
// b = {x: "Bye", y: "Test"}
// a = {x: "Hi", y: "Test"}
         


        
5条回答
  •  一整个雨季
    2021-02-19 01:11

    Two ways...

    1. You can use Object.assign:

      const a = { x: "Hi", y: "Test" }
      const b = Object.assign({}, a, { x: "Bye" });
      console.log(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 }
      console.log(b);

提交回复
热议问题