Search code examples
jqueryfor-loopvar

How to display every result of my for-loop


I'm trying to display each element of an array. My for loop is working but I can't display each result of my loop.

function newCaseTemplate(filteredCase, filteredCaseTemplate, tagList) {
  var tagList = "";

  for (var i = 0; i < filteredCase.tags.length; i++) {
    tagList = filteredCase.tags[i].name + " | ";
  }

  var filteredCaseTemplate = `<span class="index-tagsCardCase">${tagList}</span>`

  $("#index-table").append(filteredCaseTemplate);

Thanks in advance for any help !


Solution

  • You're overwriting tagList on each iteration of the loop. Use += to add to the previous string. I've also added a check not to add a pipe on the last tag.

    for (var i = 0; i < filteredCase.tags.length; i++) {
        if(i === (filteredCase.length - 1)){
            tagList += filteredCase.tags[i].name;
        }else{
            tagList += filteredCase.tags[i].name + " | ";
        }
     }