10

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.

9
  • I thinks its typescript problem not angular2. correct me if I m wrong Commented Dec 5, 2016 at 4:12
  • Do you mean deep copy or shallow copy? stackoverflow.com/questions/184710/… Commented 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? Commented Dec 5, 2016 at 4:30
  • That means you need a deep copy.Better edit the question Commented Dec 5, 2016 at 4:41
  • 3
    stackoverflow.com/questions/122102/… Commented Dec 5, 2016 at 4:46

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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?
that's why i have given the second option
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/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.