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?

1
  • Did you try console.log(copiedObject); (without the JSON.stringify)? Commented Oct 26, 2012 at 15:39

1 Answer 1

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));
});
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.