Create a deep copy in angular 2

How to create a deep copy in angular 2, I tried to use let newObject = Object.assign({}, myObject), but still myObjectdisplays all the changes made to newObject.

+4
source share
2 answers

Just use the following function:

/**
 * Returns a deep copy of the object
 */

public deepCopy(oldObj: 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;
}
+3
source

Try using Lodash.js. Since angular 2 does not have a deep copy method. for reference see: https://lodash.com/docs#cloneDeep

or you can use this javascript function

var copy = Object.assign({}, myObject);
+1
source

Source: https://habr.com/ru/post/1662801/


All Articles