How to clear a variable after one run in a for loop

Viewed 64

with my code I fetch a json from my server and display the data on the frontend. That is the json https://pastebin.com/56YEnY4Z

The code is generating a 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, 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, that code is just a snippet from the original **

1 Answers

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 = '';
Related