简体   繁体   中英

Adding objects to an object property which is an object itself with object assign

so say I have this:

const mainObject = {
  prop1: false,
  prop2: {} or []
}

const minorObject = { name: "name", address: "address" }
const minorObject2 = {name: "name2", address: "address2" }

how do add them one at time to mainObject.prop2 without mutating mainObject with Object.assign , if it is not possible then how can it be done with ES6 spread?

When you want to keep the main reference immutable you need to work with shallow copies , similar to what happen when you work with primitives.

An example with Strings (when literally declared they are treated as primitives):

 var a = 'Hello'; var b = a; b += ' World'; console.log({a, b});

As you can see, mutating b the variable a remains immutable... this because primitives are passed by value .

Because Object is not a primitive it is passed by reference and the above example becomes:

 var a = { prop: 'Hello' }; var b = a; b.prop += ' World'; console.log({a, b});

how do add them one at time to mainObject.prop2 without mutating mainObject ...?

 var a = { prop: 'Hello' } var minorA = { prop1: ' World' }; var minorB = { prop2: ' Moon' }; var b = Object.assign({}, a); //create a shallow copy Object.assign(b, minorA, minorB) // because you can pass as many params you want, you can simplify the previous code in this way: var b = Object.assign({}, a, minorA, minorB);

how can it be done with ES6 spread? The Object spread operator , that is in esnext , you can use it with babel and Object rest spread transform

var b = {...a};

Object.assign 将改变作为第一个参数传递的对象,所以如果你想组合两个对象的属性而不改变任何一个,只需将一个 Object.assign 包装在另一个中。

Object.assign(Object.assign({},mainObject),minorObject)

How to push elements of an object into another object?

Add Javascript Object into another Javascript Object

google keyword search = add an object to another object

plenty of more examples out there and ways of going about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM