1

With my code, I fetch a JSON document from my server and display the data on the frontend. That is the JSON document: https://pastebin.com/56YEnY4Z

The code is generating an HTML list.

for (var i = 0; i < data.array.length; i++) {

    if(data.array[i].orderStatus == 0)
    {
        statusName = 'Neu erstellt';
        statusColor = 'text-sky-500';
    } else if(data.array[i].orderStatus == 1) {
        statusName = 'In bearbeitung';
        statusColor = 'text-orange-500';
    }

    for(var k = 0; k < data.array[i].foodArray.length; k++) {
        li += `<li class="flex items-center justify-between"><span>` + data.array[i].foodArray[k].name + `</span><span>` + data.array[i].foodArray[k].price + ` EUR</span></li>`;
    }

    list = `<ul class="list-disc">` + li + `</ul>`;

The problem I got is that the first run is smooth, and after that, old data is getting in the second generated list. Is there a function I can use to empty the var li after one for loop run?

I declared the variables, and that code is just a snippet from the original.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cedzy
  • 46
  • 5

1 Answers1

3

You can clear your li inside the second loop if k==0, meaning every time you finish the outer loop you reset the li as k will be equal to 0 after each iteration of the outer loop

for(var k = 0; k < data.array[i].foodArray.length; k++) {
   if(k == 0)
      li = '';
   
   li += `<li class="flex items-center justify-between"><span>`+ data.array[i].foodArray[k].name +`</span><span>`+ data.array[i].foodArray[k].price +` EUR</span></li>`;
}

Or simply add at the start of your outer loop

li = '';
Osama
  • 21
  • 9