John the Painter
John the Painter

Reputation: 2615

JSON append every four values to an element (each and iterations)

I'm currently appending the data from a JSON file to an element on my site, but I need it to work in iterations of every four. So, for each element it appends, it grabs four values, then the next four and so on.

This is what I have so far:

$.getJSON('works/api', function(r) {

    var x = 0;
    $.each(r.data, function(i, work) {
        x++;
        $('.each-works-caption ul').each(function() {
            $(this).append('<li>'+ x + '. ' + work.title + '<br/><span>' + work.description + '</span></li>');
        });
    });

});

Which outputs ALL the work.title and work.description values for each JSON data, on every .each-works-caption ul but I need it to work in fours so on the first .each-works-caption ul it appends the first four values (or rows) and then on the second .each-works-caption ul it appends the second four values (or rows) and so on.

Hope this makes sense and I realise it's a little specific so I apologise in advance.

-R

Upvotes: 0

Views: 39

Answers (1)

adeneo
adeneo

Reputation: 318222

$.getJSON('works/api', function(r) {
    $.each(r.data, function(i, work) {
        $('.each-works-caption ul:eq('+Math.floor(i/4)+')').append(
            $('<li />', {html: i + '. ' + work.title +  '<br/>'}).append(
                $('<span />', {text: work.description})
             )
        )
    });
});

FIDDLE

Upvotes: 1

Related Questions