-1

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?

Jan
  • 3,393
  • 4
  • 21
  • 47

3 Answers3

1

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};
Community
  • 1
  • 1
Hitmands
  • 13,491
  • 4
  • 34
  • 69
0

Object.assign will mutate the object passed as the first argument, so if you want to combine the properties of two objects without mutating either, simply wrap one Object.assign inside another.

Object.assign(Object.assign({},mainObject),minorObject)
user3094755
  • 1,561
  • 16
  • 20
-1

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.

Community
  • 1
  • 1
Ryan Sanders
  • 141
  • 1
  • 8