Search code examples
javascriptjqueryloopsiterationmap-function

map iteration, how to get only one item per time with map function jquery


I have question about iteration through json data with $.map Below you can see my code , my goal it's append only 1 title per time with iterration (1 item 1st title; 2 title 2nd title; and so on) but right now I got all of them , when I use return $('.card-title').append(post.title[i]); I got letter from each item , can anybody help me with advise please , Thank you .

$(document).ready(function(){
$.ajax({
    method: 'GET',
    url: 'https://jsonplaceholder.typicode.com/posts',
    dataType: 'json'
    }).done(function(data){
    console.log(data);
    $.map(data, function(post ,i){
        return $('.card-title').append(post.title);
    });
 });
});

Solution

  • You can use .eq() to reference a specific index of the jQuery collection

    $(".card-title").eq(i).append(post.title);
    

    or substitute using .append(function) for $.map()

    $(".card-title").append(function(i, el) {
      return data[i].post.title
    });