0

So I have a variable called elements that hold a bunch of data. Let's say, for example, that this is it:

{
  name: "Jeff",
  age: "18",
  carList: [
    "car1": "...",
    "car2": "..."
  ],
  surname: "Matt"
}

I also have an empty array, at the start, declared this way:

public myArray: Model[] = [];

Model is just a class that contains the definition of the elements.

What I'm trying to achive is to have a copy of elements without keeping any reference to the original variable. but I'm missing something. Here's a pseudo-code that do the trick (almost) :

myfunction(){
  //Do stuff that change `car1` from `...` to `hello`
  myArray.push(Object.assign({}, this.elements));
}

And finnally a I have a function that print everything in the myArray variable:

function print(){
  this.myArray.forEach(el => {
    console.log(el);
  });
}

The problem is that every element of the array has the latest update done by me. So if myFunction was called several time doing something like:

  • Change "Jeff" to "Jack"
  • Change age "18" to "25"
  • Change surname to "Seth"

what I see is three log showing this data:

{
  name: "Jeff",
  age: "25",
  carList: [
    "car1": "...",
    "car2": "..."
  ],
  surname: "Seth"
}

My question is: Why even using Object.asign it still keeping the reference to it's original object? I should keep the history of each modification, instead of having just the last edit in both of three edits I've made.

Thank you.

Jacopo Sciampi
  • 2,990
  • 1
  • 20
  • 44

1 Answers1

3

Try the following:

JSON.parse(JSON.stringify(element));

It keeps no refrences, as you can observe in the snippet below:

let element = { name: "Jeff", age: "18", carList: [ {"car1": "x"}, {"car2": "y"} ], surname: "Matt" };

let result = JSON.parse(JSON.stringify(element));
result.name = "x";

console.log(result);
console.log("****element*****");
console.log(element);
amrender singh
  • 7,949
  • 3
  • 22
  • 28