简体   繁体   中英

Loop through jQuery array in each function not working

I have data that I get from an API in another function. To get the data I do this:

var posts = get_posts();

I can then print to the console:

console.info( posts );

I'll end up with something like this:

[]
  0: {id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1, …}
  1: {id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1, …}
  ...

There's multiple entries in this array with various bits of data.

However, if I then try to loop through them and do something, the each statement doesn't do anything. It's as if it's completely ignored (which it probably is).

$.each( posts, function( index, record ) {

    alert( index );

});

What am I doing wrong here?

Edit

This is the code I have inside a function which returns (or should) return the array. Using a simple console.log returns the data, however using stringify just returns [] .

$.each( object, function( key, value ) {

    var post = {
        id: value.id,
        ...
    };

    posts.push( post );

});

console.log( posts ); // prints the data out

JavaScript is not my strongest coding language so I'm assuming I'm setting up the data incorrectly perhaps?

It should be alright. I've put together a working example for you. Can you spot the difference between your code and the working snippet below?

 var posts = [ { name: 'Post1' }, { name: 'Post2' } ]; $.each(posts, function(index, record) { console.log(index, record); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The issue might be in the code that you're using to populate the array. Can you provide a bit more context?

You can print all the object with:

$.each( posts, function( index, record ) { alert(  JSON.stringify(record) ) });

Or specific keys using

$.each( posts, function( index, record ) { alert(  record["slug"] ) });

Run the code and see the demo

 $(function(){ var posts = []; posts.push({id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1}); posts.push({id: 123, date: "2018-01-01T12:00:00", slug: "asdf-xyz", author: 1, media: 1}); $.each( posts, function( index, record ) { alert( JSON.stringify(record) ) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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