Object.assign—override nested property

前端 未结 7 451
轮回少年
轮回少年 2020-12-13 01:36

I have an Object a like that:

const a = {
  user: {
   …
   groups: […]
   …
  }
}

whereby there are a lot more properties in

7条回答
  •  温柔的废话
    2020-12-13 02:22

    The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

    assign method will make a new object by copying from the source object, the issue if you change any method later on in the source object it will not be reflected to the new object.

    Use create()

    The Object.create() method creates a new object with the specified prototype object and properties.

    const b = Object.create(a)
    b.user.groups = {}
    // if you don't want the prototype link add this
    // b.prototype = Object.prototype 
    

    This way you have b linked to a via the prototype and if you make any changes in a it will be reflected in b, and any changes in b will not affect a

提交回复
热议问题