Search code examples
javascriptjqueryjsoneachfor-in-loop

Populate <p> tags with JSON data for in loop


I'm trying to target 18 $('.char-names') elements and dynamically populate with names from a local JSON file. The 3 console log's are showing 18 different id, charName, ingName, so the data is linking. It just populates $('.char-names') with the same name in every slot. I'm pulling my hair out here.

$.getJSON('people.json', function(data) {
    for (var i in data) {
        var charName = data[i].name;
        var imgName = data[i].image;
        var id = data[i].id;
        console.log(id);
        console.log(charName);
        console.log(imgName);

        $('.char-names').text(charName);
    }
});

The HTML...

<div class="faces-container">
    <img src="img/face1.jpg" class="faces">
    <p class="char-names"></p>
</div>

Solution

  • For starters don't use for in on arrays.

    You can use the index of the $('.char-names') elements if they are indexed the same as the array data

    $.getJSON('people.json', function(data) {
        var $charNames =  $('.char-names');
        $.each(data, function(i, obj){
              $charNames.eq(i).text(obj.name);
        });
    });
    

    If the indexing is not the same then not enough detail is provided in question