-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?

3
  • What is it you are not wanting to mutate? Commented Oct 16, 2016 at 7:40
  • do you regard mainObject.prop2 = minorObject; as a mutation ?? Commented Oct 16, 2016 at 7:42
  • i basically want to add a new copy of mainObject with the content of minorObject first. so on and so forth Commented Oct 16, 2016 at 7:47

3 Answers 3

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};
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.