For the last couple of days i have been struggling to figure out how to create a new object from a current object in my script without affecting the properties when i bind them.
For example, this is what i mean. i have obj{} and i want to create a copy for caching purposes so i don't have to call onto my API again when the data has already been fetched. this is an example of the code.
let obj = {food: { mexican: "taco"}};
let objCopy = Object.assign({}, obj
);
In my HTML template I have binded to an input:
<input type="text" [(ngModel)]="objCopy.food.mexican">
<pre>obj
: {{obj
|json}}</pre>
<pre>objCopy
: {{objCopy
|json}}</pre>
whenever I type something into the input box, the obj.food.mexican and objCopy.food.mexican properties change. What i need was to create a objCopy
without affecting (referencing) the obj
object.
The only way to copy and create a new
without referencingobjCop
obj
was to use the following code:
= JSON.parse(JSON.stringify(let objCopy
));obj
The answer was found on this post: