How To Deep Copy (clone) An Object With Array Members In Javascript?
Solution 1:
If you're dealing with custom classes, you're going to want to implement custom clone methods. Generally, in this context, I'd have 2 separate clone functions, one on the Person model and one on the Persons collection.
Persons.prototype = {
clone: function() {
var clone = new Persons();
clone.mItems = this.mItems.map(function(person) {
return person.clone();
});
return clone;
}
}
Person.prototype = {
clone: function() {
var clone = new Person(this.name);
clone.score = this.score;
return clone;
}
}
The advantage to this approach is that it separates the concerns - the Person class doesn't have to know how to clone a single Person, it only has to know that Person exposes a clone method. If Person adds a new property that should be persisted in the clone, only Person needs to change.
It's generally an anti-pattern to use generic clone methods, e.g. from jQuery or Underscore, in this context. They'll end up cloning things you don't want, or missing things you do (e.g. a Person might eventually have an Address or some other object that will also need cloning).
Solution 2:
You can use [].map and Object.assign:
Persons.prototype.clone = function() {
var clone = new Persons();
clone.mItems = this.mItems.map(function(person) {
return Object.assign(new Person, person);
});
return clone;
};
Post a Comment for "How To Deep Copy (clone) An Object With Array Members In Javascript?"