How I can create deep copy in angular 2, I tried to use let newObject = Object.assign({}, myObject) but still myObject reflects all the changes done in newObject.
-
I thinks its typescript problem not angular2. correct me if I m wrongAniruddha Das– Aniruddha Das2016-12-05 04:12:20 +00:00Commented Dec 5, 2016 at 4:12
-
Do you mean deep copy or shallow copy? stackoverflow.com/questions/184710/…Suraj Rao– Suraj Rao2016-12-05 04:13:13 +00:00Commented Dec 5, 2016 at 4:13
-
@SurajRao ok now I am also confused, I just want to reset my object to its default state when my work is done with that object. So to do that, I need to store that default copy, but when I make changes at one place all other copy also gets changed. How to prevent that?Dheeraj Agrawal– Dheeraj Agrawal2016-12-05 04:30:18 +00:00Commented Dec 5, 2016 at 4:30
-
That means you need a deep copy.Better edit the questionSuraj Rao– Suraj Rao2016-12-05 04:41:06 +00:00Commented Dec 5, 2016 at 4:41
-
3stackoverflow.com/questions/122102/…Suraj Rao– Suraj Rao2016-12-05 04:46:15 +00:00Commented Dec 5, 2016 at 4:46
|
Show 4 more comments
2 Answers
Just use the following function :
/**
* Returns a deep copy of the object
*/
public deepCopy(oldObj: any) :any {
var newObj = oldObj;
if (oldObj && typeof oldObj === "object") {
newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
for (var i in oldObj)
newObj[i] = this.deepCopy(oldObj[i]);
}
return newObj;
}
Comments
Try to use the Lodash.js . Because angular 2 does not have any method for deep copy . for reference see :https://lodash.com/docs#cloneDeep
or You can use this javascript function
var copy = Object.assign({}, myObject);
3 Comments
Playdome.io
Do you think including lodash just for this one feature is reasonable? To add 2 numbers would you install math.js? So would you keep adding random third party libraries for every trivial task you run into?
Jitendra gupta
that's why i have given the second option
Playdome.io
I know but that is wrong sadly.. Please see the documentation: Warning for Deep Clone For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value. developer.mozilla.org/en/docs/Web/JavaScript/Reference/…