Search code examples
javascriptjqueryjsonwordpresswordpress-rest-api

Loop through WP REST API AJAX Array using jQuery


I am trying to loop through a AJAX array that was created from the WP REST API. I have no trouble at all returning the data from the first post in the array:

$( '#button' ).on( 'click', function ( e ) {
            e.preventDefault();
            $.ajax( {
              url: 'http://url.com/wp-json/posts?type=post&filter[posts_per_page]=20',
              success: function ( data ) {
                var post = data.shift(); // The data is an array of posts. Grab the first one.

                    $( '.item .front_feed_title' ).text( post.title );
                    $( '.item .front_feed_content' ).html( post.content );

              },
              cache: false
            } );
          } );

However, I need to loop through the AJAX array and I am unable to figure out the syntax that works for that. I want to pass data into a .each function This does not work:

$( '#button' ).on( 'click', function ( e ) {
            e.preventDefault();
            $.ajax( {
              url: 'http://url.com/wp-json/posts?type=post&filter[posts_per_page]=20',
              success: function ( data ) {

                 $.each([data], function(i, objects) {

                     console.log(i.title);

                 });

              },
              cache: false
            } );
          } );

My console says that the object is undefined. Can anyone provide some insight into how I should pass data into a jQuery .each function?


Solution

  • Without knowing your objects structure it's kind of hard to say but try. Inside the function 'this' refers to the current object. So you can reference elements like this.KEY

    $.each(data,function(){
    
    console.log( this.title ,this.content);
    
    })