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

后端 未结 5 2060
没有蜡笔的小新
没有蜡笔的小新 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 00:55

    Try this : const b = a.map(item => Object.assign({}, ...item)); This will create a new object without any reference to the old object a

    In case if you want to do this for an array try the same with []

    const b = a.map(item => Object.assign([], ...item));
    
    0 讨论(0)
  • 2021-02-19 01:06

    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"}; 

    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2021-02-19 01:11

    Es6 has a built in function for copying object properties, Object.assign

    const b = Object.assign({}, a, {x: 'Bye'})
    

    here we create an empty object, push all of as key value pairs in, followed by the new key value pairs we want to over write. because the empty object is the first argument, we mutate that object, not a

    0 讨论(0)
  • 2021-02-19 01:13

    Create a copy of the object and change the copy:

    const b = Object.assign({}, a, {x: "Bye"})
    

    Docs for Object.assign()

    0 讨论(0)
提交回复
热议问题