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

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

    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

提交回复
热议问题