0

I am running into this issue, when i use Object.assign() previous value getting overridden.

var blueprint = {
 name: {
   first: "Default first name",
    last: "Default last name"
  }
};

var person1 = Object.assign( {}, blueprint );

console.log( blueprint.name.first ); // Gives me "Default first name"

person1.name.first = "John";

console.log( blueprint.name.first ); // Gives me "John"
console.log( blueprint.name.last ); // Gives me "Default last name"

Question is how can i override person1.name.first while keep my blueprint safe?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Tpn Knvl
  • 43
  • 4
  • 1
    The question is missleading. By reading it I though that just using the function resulted in the source object being mutated. Please reformulate. Btw, the problem is relatated to the fact that Object.assign does not make a deep copy of the source object – Jota.Toledo Feb 11 '18 at 14:05
  • 1
    You need to make a copy of the `.name` object as well, i.e. `person1.name = Object.assign({}, blueprint.name);` – Bergi Feb 11 '18 at 14:06
  • 1
    You have to deep copy the source objects like this `var newObj = JSON.parse(JSON.stringify(blueprint));`. – Navoneel Talukdar Feb 11 '18 at 14:09

0 Answers0