Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 = '';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading