简体   繁体   中英

Pushing objects to an array from JSON

I'm trying to get 3 different facebook feeds and put them into one single object. The object is item, and it has the time the post was created, and the actual data object itself from the JSON package. When i log the items array, it shows only 5 items when i check the log, but when i expand the array inside the log, it shows all 15 items that i pushed. calling items[0] to 4 works, but after that it says the item is undefined. I'm not quite sure what im doing wrong as it seems like all the data is in the items array.

function item(time, obj)
{
    this.time = time;
    this.obj = obj;
}

    $(document).ready(function() {
        var items = [];
        $.getJSON("http://feed1", function(obj) {                   
            $.each( obj.data, function( key, val ) {
                items.push(new item(val.created_time,val));
            });
        }); 
        $.getJSON("http://feed2", function(obj) {                   
            $.each( obj.data, function( key, val ) {
                items.push(new item(val.created_time,val));
            });
        });
        $.getJSON("http://feed3", function(obj) {                   
            $.each( obj.data, function( key, val ) {
                items.push(new item(val.created_time,val));
            }); 
            console.log(items); // shows 5 items, but expanded, shows 15 while inspecting
            console.log(items[0].time); // Works
            console.log(items[5].time); // Fails
        });
            console.log(items);  // shows an empty items array
    });

Ajax is async, so when you do your console.log() statements, it's possible that not all of the calls have finished. A simple solution to your problem would be to get each request's promise and wait for all of them to finish:

$(document).ready(function () {
    var items = [];
    var feed1 = $.getJSON("http://feed1", function (obj) {
        $.each(obj.data, function (key, val) {
            items.push(new item(val.created_time, val));
        });
    });
    var feed2 = $.getJSON("http://feed2", function (obj) {
        $.each(obj.data, function (key, val) {
            items.push(new item(val.created_time, val));
        });
    });
    var feed3 = $.getJSON("http://feed3", function (obj) {
        $.each(obj.data, function (key, val) {
            items.push(new item(val.created_time, val));
        });        
    });

    $.when(feed1, feed2, feed3).done(function() {
        console.log(items); 
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM