2

How to fully copy / overwrite an object using Object.assign()? If there would be another approach, it would be highly appreciated. :) The purpose is to update the existing object to its new value.

Below is my code snippet and the expected result should be the same as the value of object2 only.

Expected result: { a: 8, b: 7 }

const object1 = {
  a: 1,
  b: 2,
  c: {
    d: 3
  }
};

const object2 = {
  a: 8,
  b: 7
};

Object.assign(object1, object2);

console.log(object1);

3
  • 5
    It sounds like you just want to copy object2 and completely discard the existing object1? You shouldn't use Object.assign for that Commented Jul 31, 2018 at 6:52
  • 1
    note that you can't completely replace object1 since it was declared with const. Commented Jul 31, 2018 at 6:53
  • 5
    Where do any arrays come into this? Commented Jul 31, 2018 at 6:53

2 Answers 2

4

For keeping the same object reference, you could remove all properties in advance and then assign the wanted properties with Object.assign.

const object1 = { a: 1, b: 2, c: { d: 3 } };
const object2 = { a: 8, b: 7 };

Object.assign(
    Object.keys(object1).reduce((o, k) => (Reflect.deleteProperty(o, k), o), object1),
    object2
);

console.log(object1);

IE

var object1 = { a: 1, b: 2, c: { d: 3 } },
    object2 = { a: 8, b: 7 };

Object.keys(object2).reduce(
    function (object, key) {
        object[key] = object2[key];
        return object;
    }, 
    Object.keys(object1).reduce(function (object, key) {
        delete object[key];
        return object;
    }, object1)
);

console.log(object1);

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

3 Comments

Hi @Nina Scholz, i found out that deleteProperty is not supported in IE :( is there any other option which works also in IE?
it does not support const and arrow functions as well, nor Object.assign.
Wow! I tried the other one for IE and it works! thank you so much again!!!
0

If you want to override the object1 properties with those from object2, you need to do it like this:

object1 = Object.assign({}, object2);

But with this you need to declare object1 with var keyword so you can assign a new value to it.

Demo:

var object1 = {
  a: 1,
  b: 2,
  c: {
    d: 3
  }
};

const object2 = {
  a: 8,
  b: 7
};

object1 = Object.assign({}, object2);

console.log(object1);

2 Comments

@KimCindy LikeI said, you need to change the declaration from const object1 = to var object1=, check the Demo on my answer.
Yes, on my project it was not declared as const. I tried but the source object doesn't update.

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.