-1

How to assign/clone received JSON object to previously defines JavaScript Object booksJSON ? I need to make booksJSON accessible and visible for all functions.

var booksJSON = {};
    function getBooks(){
    $.getJSON( "bookstore.json", function( json ) {

        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON  =  json;  // CLONE OBJECTS 
   });
}

UPDATE:

New code:

    var booksJSON = {};
function getBooks(){
    return $.getJSON( "bookstore.json" );
}


$(document).ready(function(){

     getBooks();
     getBooks().done(function(json) {
        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON = json;
        alert(JSON.stringify(booksJSON));
    });

});
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185

1 Answers1

3

It has nothing to do with cloning! $.getJSON is asynchronous and you can't use the data before it's available once the $.getJSON function has completed, and that's what the success callback is there for.

var booksJSON = {};
function getBooks(){
    $.getJSON( "bookstore.json", function( json ) {

        /* This is an async function, it executes at a later time */

        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON  =  json;  // here json is available
   });
   console.log( booksJSON ); // this happens before the above function, 
                             // so here booksJSON is still an empty object, 
                             // as nothing has been added yet
}

The only thing you can do is something like :

function getBooks(){
    return $.getJSON( "bookstore.json" );
}

getBooks().done(function(json) {
    $.each(json.books, function(i, json){
        renderEntity(json);
    });
});

If that helps any ?

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I think `function( json ){...}` is executed after json received because I have valid json object passed to `renderEntity(json);`. Then why if I use `booksJSON = json;` it returns empty object? – J.Olufsen Apr 08 '13 at 22:35
  • getBooks().done nice!! didnt know you can do that... – ncubica Apr 08 '13 at 22:59