0

I'm trying to add new properties to obj sub in object1. However its getting overwritten

const object1 = {
  a: 1,
  b: 2,
  c: 3,
  sub: {
    e: 1,
    f: 2
  }
};

const object2 = Object.assign({
  j: 4,
  m: 5
}, object1.sub);

console.log(object2);

1
  • How do you mean "getting overwritten"? I would expect this to log { e:1, f:2, j:4, m:5 }? The way you have it written, you are taking object { j: 4, m: 5 } and adding the properties from object1.sub to it, then assigning that to object2. Commented Apr 3, 2018 at 20:20

2 Answers 2

6

You could switch the parameters for Object.assign, because the target is coming first.

const object = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } };

Object.assign(object.sub, { j: 4, m: 5 });

console.log(object);

Sign up to request clarification or add additional context in comments.

Comments

1

With ES6 syntax:

const object1 = { a: 1, b: 2, c: 3, sub: { e: 1, f: 2 } };
const object2 = {...object1, sub: {...object1.sub, j: 4, m: 5}}
console.log(object2)

2 Comments

did you test it ?
oops2, got it now

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.