Answer the question
In order to leave comments, you need to log in
How to create 2 identical independent objects in JavaScript?
Faced the following problem - I create 2 objects. I change properties in one object - they change in another. How to make them independent, even if they are based on the same set of initial data?
function Item(coordinates){
this.coordinates = coordinates || false;
this.moveItemToAValueBelow = function(value){
for (var i in this.coordinates){
this.coordinates[i][1]+=value;
}
}
}
var first = new Item(data);
var second = new Item(data);
second.moveItemToAValueBelow(20);
console.log(first.coordinates);
console.log(second.coordinates);
Answer the question
In order to leave comments, you need to log in
You should have started with what kind of data you have. I looked at github - you have nested arrays.
In this case, @ghaiklor's option wo n't work because it's only for flat objects.
data.slice(0) won't work either, because only the first level of the array will be unique.
Try JSON.parse(JSON.stringify(data))
Your objects are independent, but you pass the same data instance to the constructors, i.e. you have coordinates one for two objects.
JavaScript does not have a standard method for doing "deep cloning".
If you're using jQuery, you can try this.coordinates = $.extend({},coordinates).
Or write your own clone() in pure JS
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
this.coordinates = clone(coordinates);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question