3

I've looked into the many posts here regarding cloning and copying javascript objects, notably, these two topics:

It seems like it's not working for me, though.

Here is a snippet of code I'm using:

var copiedObject = {};

$.getJSON(URL, null, function (data) {
     copiedObject = jQuery.extend(true, {}, data);
});

console.log(JSON.stringify(copiedObject));

If I have my console log function within the JSON call, it outputs the proper values, but after the function, it's emptied out, and outputs {}.

I've tried using copiedObject = JSON.parse(JSON.stringify(data)), as well as the clone(obj) function from the "Copying an object in Javascript" post, all to no avail.

Am I missing something?

Community
  • 1
  • 1
D'Arcy Rail-Ip
  • 11,505
  • 11
  • 42
  • 67

1 Answers1

8

$.getJSON fires an Ajax request, which by default runs asyncronous. Your console.log will fire before the request has finished. Fix it by moving the console output into the callback.

$.getJSON(URL, null, function (data) {
     copiedObject = jQuery.extend(true, {}, data);
     console.log(JSON.stringify(copiedObject));
});
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Thank you, but will my object retain it's values outside of that function? I'm trying to limit the number of times I have to make this ajax request. – D'Arcy Rail-Ip Oct 26 '12 at 15:44
  • 1
    @Rail24: yes. If `copiedObject` is contained by a higher parent scope, you can access its value in any child-scope. All you need to make sure is, that every piece of code which accesses that variable executes *after* the request has finished. – jAndy Oct 26 '12 at 15:46