How can I copy an object and lose its reference in Angular?
With AngularJS, I can use angular.copy(object)
, but I\'m getting some error using that in An
The alternative for deep copying objects having nested objects inside is by using lodash's cloneDeep method.
For Angular, you can do it like this:
Install lodash with yarn add lodash
or npm install lodash
.
In your component, import cloneDeep
and use it:
import { cloneDeep } from "lodash";
...
clonedObject = cloneDeep(originalObject);
It's only 18kb added to your build, well worth for the benefits.
I've also written an article here, if you need more insight on why using lodash's cloneDeep.
The simplest solution I've found is:
let yourDeepCopiedObject = _.cloneDeep(yourOriginalObject);
*IMPORTANT STEPS: You must install lodash to use this (which was unclear from other answers):
$ npm install --save lodash
$ npm install --save @types/lodash
and then import it in your ts file:
import * as _ from "lodash";
Till we have a better solution, you can use the following:
duplicateObject = <YourObjType> JSON.parse(JSON.stringify(originalObject));
EDIT: Clarification
Please note: The above solution was only meant to be a quick-fix one liner, provided at a time when Angular 2 was under active development. My hope was we might eventually get an equivalent of angular.copy()
. Therefore I did not want to write or import a deep-cloning library.
This method also has issues with parsing date properties (it will become a string).
Please do not use this method in production apps. Use it only in your experimental projects - the ones you are doing for learning Angular 2.
let newObj = JSON.parse(JSON.stringify(obj))
The JSON.stringify()
method converts a JavaScript object or value to a JSON string
If you want to copy a class instance, you can use Object.assign too, but you need to pass a new instance as a first parameter (instead of {}) :
class MyClass {
public prop1: number;
public prop2: number;
public summonUnicorn(): void {
alert('Unicorn !');
}
}
let instance = new MyClass();
instance.prop1 = 12;
instance.prop2 = 42;
let wrongCopy = Object.assign({}, instance);
console.log(wrongCopy.prop1); // 12
console.log(wrongCopy.prop2); // 42
wrongCopy.summonUnicorn() // ERROR : undefined is not a function
let goodCopy = Object.assign(new MyClass(), instance);
console.log(goodCopy.prop1); // 12
console.log(goodCopy.prop2); // 42
goodCopy.summonUnicorn() // It works !
If you are not already using lodash I wouldn't recommend installing it just for this one method. I suggest instead a more narrowly specialized library such as 'clone':
npm install clone