Unending Jquery Loop Iteration

I encountered a bug while writing code to display JSON data in an HTML table. Even though I only have 25 IDs to print from the JSON, my code is printing them more than 10 times when it should run only once. I tried adding breakpoints in the code but still can't find the bug.

Here's the 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>

Answer №1

The problem arises because nested loops are being used through data. One loop is using $.each(data, fn) and another one inside that is using data.forEach(fn). It's better to combine these loops:

function fetch_user_data() {
  $.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="fetch_user_data()">CLICK</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript - Editing specific markers with varying titles from the url

My website contains checkboxes in the html code: <input onclick="markAsChanged(this); toggleApproveDeny(this);" name="2c9923914b887d47014c9b30b1bb37a1_approveChk" type="checkbox"> <input onclick="markAsChanged(this); toggleApproveDeny(this);" na ...

Loop through and store data in Node.JS within an array

Initially, I attempted to use a simple for loop to iterate through the data. However, this approach didn't work due to the nature of request.save being a function. After some experimentation, I decided to utilize forEach instead. Everything seemed to ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

I am facing unexpected results while trying to search for a string array object using elemMatch in Mongoose

I am encountering an issue that I can't seem to resolve. I need to utilize a query search to match the data of one job with user data, but I'm facing some obstacles. The primary challenge is within my query search for the job where the data looks ...

Retrieve a designated text value from a Promise

I have developed a React/Next.js application that utilizes what3words to assign items to specific locations. The code I've created processes the what3words address, converts it into coordinates, and is intended to display the location on a Mapbox map. ...

What is the process for generating and parsing an XML file using jQuery?

I've come across a lot of information on creating and sending XML files with Ajax, but I'm feeling pretty confused. My goal is to generate an XML file and send it to the server using Ajax. In return, I expect to receive another XML file. Below ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Is there a way to add animation effects when transitioning between sections in HTML?

Recently, I decided to incorporate sections into my website, but I am not a fan of how it simply jumps to the designated section. I have observed on some websites that when you click a button to move to another section, it smoothly slides down. Despite c ...

Exploring a JavaScript file with the power of JavaScript and HTML

I have a .js file that contains the following data (excerpt for brevity) var albums= "tracks":[ {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3", "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from t ...

Expand the clickable area of the checkbox

Is it possible to make clicking on an empty space inside a table column (td) with checkboxes in it check or uncheck the checkbox? I am limited to using only that specific td, and cannot set event handlers to the surrounding tr or other tds. The functional ...

Ways to achieve perfect alignment for SVG text within its container, as opposed to stretching across the entire webpage

Recently, I've been working on a customizable photo frame designer using SVG. One of the key features allows users to add their own text to the frame. To achieve this, I'm utilizing jQuery's .keyup function. However, the issue I'm facin ...

Deactivate the collapse toggle feature in the footer navigation

I've recently started using bootstrap and I'm having some trouble adding a social nav footer to my portfolio. I've experimented with removing different classes and even tried using the sticky footer feature, but it's not quite what I ne ...

Assessing personalized directive attributes

I am currently working on a custom directive that will activate a specified event when a particular expression evaluates as true. The code below demonstrates how it can be achieved when binding a single value- <div ng-trigger="value.someBoolean" /> ...

Troubleshooting Nested Handlebars Problem

After creating a customized handlebar that checks for equality in this manner: Handlebars.registerHelper('ifEquals', (arg1, arg2, options) => { if (arg1 == arg2) { return options?.fn(this); } return options?.inverse(t ...

Is there a way to prevent my Header links from wrapping during window size testing?

https://i.stack.imgur.com/YTc3F.png The image above showcases my standard header layout, while the one below illustrates what occurs as I resize the window. https://i.stack.imgur.com/re44T.png Is there a specific CSS solution to prevent the Text navLink ...

How can I access multiple icons using jQuery?

Below is the JavaScript code I am using: $(document).ready(function() { $.getJSON("Stations.php", function(jsonData){ $.each(jsonData, function(key,value) { $('#selectStation') .append($("<option></option>") ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Adding DIV elements within a Bootstrap Carousel

I've successfully placed containers inside my Bootstrap Carousel slides that overlay the image with text and a link. It looks great initially, but I'm facing an issue where after switching to the next slide, I can't return to the one with th ...

What is the method for implementing tooltips using JQuery?

AJAX call returns data for dropdown lists 'list1' and 'list2'. If there is no data available, I want to hide the dropdowns with `pointer-events: none` and display a tooltip that says "Data not available". else if (monthly_list.lengt ...