3

I am using a plain JavaScript object. I have to create an exact copy of the object to make changes:

var gRoll = {a:"pankaj",b:
{
a:"A",b:"c"
}} 

var copy = gRoll;
copy.a = "Karma";

This is making change in the parent object. Please give me solution to create copy of the object without referring to the old one. Same like prototype design pattern in OOPS.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pankaj786
  • 269
  • 3
  • 16
  • 2
    maybe you wanna check http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object Cheers – Lemmerich May 07 '14 at 13:02

2 Answers2

2

You're referencing the same object with copy

var gRoll = {
    a:"pankaj",
    b:{a:"A",b:"c"}
}
var newObject = Object.create(gRoll);
newObject.a = 'Karma';

alert(gRoll.a); //pankaj
alert(newObject.a); //Karma
xxx
  • 182
  • 7
  • 1
    If you mutate members of newObject it affects gRoll: `newObject.b.a="changed"; console.log(gRoll.b.a);//=changed` This because Object.create doesn't clone but sets gRoll as newObject's prototype. More on how that works here: http://stackoverflow.com/a/16063711/1641941 Making a deep copy or clone is complicated in JavaScript. – HMR May 07 '14 at 15:08
0

what you are doing is not creating a copy but referring to the existing object with a new variable, hence the issue.

If you are using jQuery, use its extend() method which copies an exiting object... with optional parameter for deep-copying. http://api.jquery.com/jquery.extend/

Aditya Jain
  • 1,077
  • 1
  • 12
  • 25