Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an array of objects?

I am trying to create a stamp duty calculator.

Currently, I have an array of objects containing 3 properties, every object has the same property name but different values.

I am trying to loop through this array to append property 1 and 2 to a table row if a button is clicked, however the loop appends only the first object properties and not the others.

I know there have been similar queries but none of them have helped. I'm sure there is something simple I am missing.

I have also attached an img for a better understanding of the problem

enter image description here

here is my code

         var taxbands = [
         {
             min: 0,
             max: 125000,
             percent: 0
         },
         {
             min: 125000,
             max: 250000,
             percent: 0.02
         },
         {
             min: 250000,
             max: 925000,
             percent: 0.05
         },
         {
             min: 925000,
             max: 1500000,
             percent: 0.1
         },
         {
             min: 1500000,
             max: null,
             percent: 0.12
         }
     ]

     var tableRow = "<tr><td>{taxband}</td><td>{percent}</td><td>{taxable}</td><td>{TAX}</td></tr>";

     $('#calculate').on('click', function calculateButton() {
        calculateStampDuty();
     })

     function calculateStampDuty() {

        var userInput = parseInt($("#input-value").val());

        for (i = 0; i < taxbands.length; i++) {
            if (userInput < 125000) {
                tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(tableRow);
            }
        }

     }
like image 977
Sai Avatar asked Jul 24 '26 19:07

Sai


1 Answers

that's because you assign the replaced value of "tableRow" back to "tableRow". After the first iteration, tableRow doesn't contain "{taxband}" anymore, and replace has no effect.

tableRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(tableRow);

You should instead add an intermediate variable:

var myRow = tableRow.replace("{taxband}", taxbands[i].min + "-" + taxbands[i].max);
                $("#explained-table").append(myRow );
like image 189
Regis Portalez Avatar answered Jul 26 '26 09:07

Regis Portalez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!