Ritik Singh
Ritik Singh

Reputation: 385

Jquery Loop running infinte

I was writing some code for printing json data in html table. Everything is working good but there is a bug i am not able to resolve. I have only 25 ids to print from json. But my code is printing 25 ids for more than 10 times. But it should run only for once. I have apllied breaking points in code but still unable to locate that bug. Here is my full file code with html and css

HTML

      <table id='userdata'>
        <thead>
            <tr>

                <th colspan="4" id="que">Question</th>
                <th id="user">User Info</th>
            </tr>
            <tr>

                <th>Id</th>
                <th>isActive</th>
                <th>is Complex</th>
                <th>is Breakdown</th>
                <th>USER</th>

            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <button onclick="get_testser_info()">CLICK</button>
</body>

This is my JS

  function get_testser_info() {
      $.ajax({
          type: 'GET',
          url: 'https://api.myjson.com/bins/fh4d0',
          data: { get_param: 'value' },
          dataType: 'json',
          success: function (data) {
              console.log(data);
              var people = [];
              var ctCells = [], questionCells = [], userCells = [];
              var $tBody = $("#userdata tbody");
              $.each(data, function (i, f) {
                  var users = []
                  var question = []   
                  f.user_info.forEach((x) => {


                      //avoid duplicates
                      console.log("y=================", x)
                      var foundUser = users.find((user) => {
                          return user.id === x.id
                      })
                      if (!foundUser) {
                          users.push(x)
                      }

                  })
                  f.user_info.forEach((x) => {
                      var foundQuestion = question.find((questions) => {
                          return questions.id === x.id
                      })
                      if (!foundQuestion) {
                          question.push(x)
                      }
                  })
                  console.log(f.user_info)
                  data.forEach(value => {
                      ctCells.push(`<td colspan="2">&nbsp;</td>`)
                      questionCells.push(`<td id=${value.id}>${value.id}</td><td>${value.is_active}</td><td>${value["is_complex"]}</td><td>${value["is_broken_down_specific"]}</td><td>


              ${value.user_info.map(valueData => {
                          return `<div style="display:flex; flex-direction:column;border-right: 1px solid;padding-right: 10px;">
                                <div style="text-align:left"><b style="color: red">Id</b>&nbsp;&nbsp${valueData.id}<br><b style="color: red">Name</b>&nbsp;&nbsp${valueData.name}</div>
                                  <div style="text-align:left"><b>UpdatedAt</b>&nbsp;&nbsp${valueData.updatedAt}</div>
                                  <div style="display:flex; flex-direction:column; padding-top: 20px;">
                                          ${valueData.data.map(IN => {
                              return `  
                                              <div style="display:flex; flex-direction:row;">
                                                <div style="overflow-x: scroll;overflow-y: hidden;white-space: nowrap;width: 100px; margin-left: 10px">${IN.git_ids}</div>

                                                <div style="width: 100px; margin-left: 10px"><span style="text-transform: capitalize; white-space: initial;"> ${Object.keys(IN)[0].replace(/_/g, " ")}</span></div>
                                                  <div style="padding-left: 20px;">${((IN)[0] == true)  ? `<i class="fa fa-check-circle" aria-hidden="true"></i>`: `<i class="fa fa-times" aria-hidden="true"></i>`}</div>
                                                  </div>`
                          })}
                                      </div>
                                  </div>`//end of return 
                      })
                      }
                      </div></td>`)// end of return

              })

              }); //end of foreach
              console.log(ctCells)
              $.each(ctCells, function (i) {

                  $tBody.append(`<tr> ${questionCells[i]}</tr>`)
              })


          }
      }); //ajax end 

  }

CSS

<style>
    #scrlSec {
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;

    }

    /* .checkSec { width: 60%;  } */
    #userdata {
        background-color: #f1f1f1;
    }

    #user {
        overflow: auto;
    }

    .flex-container {
        display: flex;
    }

    th,
    td {
        font-weight: normal;
        padding: 5px;
        text-align: center;
        width: 120px;
        vertical-align: top;
    }

    th {
        background: #00B0F0;
    }

    tr+tr th,
    tbody th {
        background: #DAEEF3;
    }

    tr+tr,
    tbody {
        text-align: left
    }

    table,
    th,
    td {
        border: solid 1px;
        border-collapse: collapse;
        table-layout: fixed;
    }
</style>

Upvotes: 1

Views: 49

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

The issue is because you have nested loops through data. One using $.each(data, fn) and the other inside that using data.forEach(fn). Combine those loops:

function get_testser_info() {
  $.ajax({
    type: 'GET',
    url: 'https://api.myjson.com/bins/fh4d0',
    data: {
      get_param: 'value'
    },
    dataType: 'json',
    success: function(data) {
      var people = [],
        ctCells = [],
        questionCells = [],
        userCells = [],
        $tBody = $("#userdata tbody");

      $.each(data, function(i, f) {
        var users = []
        var question = []
        f.user_info.forEach((x) => {
          var foundUser = users.find((user) => {
            return user.id === x.id
          })
          if (!foundUser) {
            users.push(x)
          }
        })

        f.user_info.forEach((x) => {
          var foundQuestion = question.find((questions) => {
            return questions.id === x.id
          })
          if (!foundQuestion) {
            question.push(x)
          }
        })

        ctCells.push(`<td colspan="2">&nbsp;</td>`)
        questionCells.push(`<td id=${f.id}>${f.id}</td><td>${f.is_active}</td><td>${f["is_complex"]}</td><td>${f.is_broken_down_specific}</td><td>
         

                ${f.user_info.map(valueData => {
                            return `<div style="display:flex; flex-direction:column;border-right: 1px solid;padding-right: 10px;">
                                  <div style="text-align:left"><b style="color: red">Id</b>&nbsp;&nbsp${valueData.id}<br><b style="color: red">Name</b>&nbsp;&nbsp${valueData.name}</div>
                                    <div style="text-align:left"><b>UpdatedAt</b>&nbsp;&nbsp${valueData.updatedAt}</div>
                                    <div style="display:flex; flex-direction:column; padding-top: 20px;">
                                            ${valueData.data.map(IN => {
                                return `  
                                                <div style="display:flex; flex-direction:row;">
                                                  <div style="overflow-x: scroll;overflow-y: hidden;white-space: nowrap;width: 100px; margin-left: 10px">${IN.git_ids}</div>

                                                  <div style="width: 100px; margin-left: 10px"><span style="text-transform: capitalize; white-space: initial;"> ${Object.keys(IN)[0].replace(/_/g, " ")}</span></div>
                                                    <div style="padding-left: 20px;">${((IN)[0] == true)  ? `<i class="fa fa-check-circle" aria-hidden="true"></i>`: `<i class="fa fa-times" aria-hidden="true"></i>`}</div>
                                                    </div>`
                            })}
                                        </div>
                                    </div>`//end of return 
                        })
                        }
                        </div></td>`) // end of return
      });
      $.each(ctCells, function(i) {

        $tBody.append(`<tr> ${questionCells[i]}</tr>`)
      })


    }
  }); //ajax end 

}
#scrlSec {
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}


/* .checkSec { width: 60%;  } */

#userdata {
  background-color: #f1f1f1;
}

#user {
  overflow: auto;
}

.flex-container {
  display: flex;
}

th,
td {
  font-weight: normal;
  padding: 5px;
  text-align: center;
  width: 120px;
  vertical-align: top;
}

th {
  background: #00B0F0;
}

tr+tr th,
tbody th {
  background: #DAEEF3;
}

tr+tr,
tbody {
  text-align: left
}

table,
th,
td {
  border: solid 1px;
  border-collapse: collapse;
  table-layout: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
  <thead>
    <tr>
      <th colspan="4" id="que">Question</th>
      <th id="user">User Info</th>
    </tr>
    <tr>
      <th>Id</th>
      <th>isActive</th>
      <th>is Complex</th>
      <th>is Breakdown</th>
      <th>USER</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<button onclick="get_testser_info()">CLICK</button>

Upvotes: 2

Related Questions