The best way to clone an object in javascript is to use $.extend(). We can use it in two ways:-
1.Shallow copy
2.Deep copy
1.The syntax for shallow copy is: var newObject = jQuery.extend({}, oldObject);
2.The syntax for deep copy is: var newObject = jQuery.extend( true, {}, oldObject);
Here is an example code using deep copy:-
var something = {
name: me,
age: 30
};
var example = $.extend(true, {}, something);
example.name = you;
console.log(something);
console.log(example);
Now If you try the above function, youll see that once something has been cloned as example, modifying values on example wont change the original values on something.
We can also make a COPY using JSON parse and stringify :
var data_copy = JSON.parse(JSON.stringify( original_data ));
But in some circumstances it will not work where the object contains the reference to itself. It will throw an error in that case.
Therefore deep copy is the best way to clone an object in javascript.
0 Comment(s)