JavaScript : Cloning object
One fine day, Every thing was moving smoothly,Until a basic assignment operation failed. 😐
I’m here trying to clone an object to another.
a = { "val" : 10}
{val: 10}
b = a
{val: 10}
b.val = 30
30
a -> {val: 30}
A basic operation where assigning value made me debug everything for hours.
both the variables reference the same object. Thus change in one is reflected to the other.
Later I found, As the value of a which was assigned to b. Any change in b is reflected to a at the same time.
How to solve this??
There can be multiple ways. I’m here listing three ordered by their performance.
1. Query.extend
using : jQuery.extend( [deep ], target, object1 [, objectN ] )
or
jQuery.extend( target [, object1 ] [, objectN ] )
In case of complex objects, deep = true decreases the performance.
var a = {"a" : 10};
var b = {};
jQuery.extend(true, b, a);
2.Object.assign.
var a = {"a" : 10};
var b = {};
Object.assign(b,a);
3.JSON.parse(JSON.stringify());
var a = {"a" : 10};
var b = {};
b = JSON.parse(JSON.stringify(a));
this is not a big issue but for people who are new with JavaScript, this can be a pain .
You are not having a parent here at all, there is no inheritance involved in you code… Instead, what you initially wanted to achieve is a “clone” function in JavaScript.
You have multiple options here, some of them would be (the order would be my preference):
Basically, you have chosen option 4. I’d try to avoid this option because it could have some performance drawbacks, unless you really can’t use any of the other options. However, this also depends on the objects you want to clone and on how well you know their structures…
UPDATE:
I can see you updated both the title and the content after my hints (see above), and that makes my comment look kinda strange now. Anyway...
You've added some performance measures. Keep in mind that your performance measures are quite simple, i.e. your object structures are not really complex.
Hi Nabi Zamani ,
Thanks for your valuable comment. Its great that you cleared my concept here. 🙂
Can you please clear why this behavior happens. People are saying its reference which is changing.
I cannot find a satisfying answer for the changing values.
Best Regards
Gopal.
Your assumption is correct: both your variables reference the same object.
This is pretty much similar to other languages, i.e. like Java... And just like in other languages you can implement your own clone API in JavaScript (maybe like in Java, where your class could implement the Clonable interface etc...)
Hint: SAPUI5 works with "clones" as well, and as you know SAPUI5 is JavaScript...
And here it is! Another learning blog. I read the blog not knowing what to expect, and find an awesome comment.
I really like it when the person writing the blog and the person reading it can learn.
Thank you Nabi Zamani and Gopal Anand
Michelle
Using ES6 it can be done even simpler