Achieving loop functionality with a JSON JavaScript array

I'm having trouble with this code as it only retrieves the first data from the JSON and then stops processing. I've tried simplifying it by starting over, but I can't seem to figure out what's missing. It feels like there's a simple mistake that I'm overlooking. For instance, I have removed the meta, ref, and jQuery elements for clarity.

<html>
<head>
</head>
<body>
    <table class="table table-striped">
        <tr class="bg-info">
            <th>User</th>
            <th>Name</th>
            <th>OS</th>
            <th>SN</th>
        </tr>
        <tbody id="myTable">
        </tbody>
    </table>
    <script>
        const jsonData2 = {
            "result": [{
                "data": [{
                    "user": "admin",
                    "name": "Frank Admin",
                    "OS": "Windows",
                    "sn": "yadayoda123"
                }, {
                    "user": "root",
                    "name": "john root",
                    "OS": "OS/2",
                    "sn": "123-A"
                }]
            }]
        }
    </script>
    <script>
        buildTable(jsonData2)
        function buildTable(data2) {
            var table = document.getElementById('myTable')
            for (var i = 0; i < name.length; i++) {
            }
            Object.entries(data2.result).forEach(([name, details]) => {
                console.log("gotname?", details.data[i]);
                console.log("whats i", i);
                var row = `<tr>
              <td>${details.data[i].name}</td>
              <td>${details.data[i].user}</td>
              <td>${details.data[i].os}</td> 
              <td>${details.data[i].sn}</td> 
            </tr>`
                table.innerHTML += row
            });
        };
    </script>
</body>
</html

Answer №1

A misplaced } in the loop caused an issue with limiting the loop based on data2.result.length

<body>
    <table class="table table-striped">
        <tr class="bg-info">
            <th>User</th>
            <th>Name</th>
            <th>OS</th>
            <th>SN</th>
        </tr>
        <tbody id="myTable">
        </tbody>
    </table>
    <script>
        const jsonData2 = {
            "result": [{
                "data": [{
                    "user": "admin",
                    "name": "Frank Admin",
                    "OS": "Windows",
                    "sn": "yadayoda123"
                }, {
                    "user": "root",
                    "name": "john root",
                    "OS": "OS/2",
                    "sn": "123-A"
                }]
            }]
        }
    </script>
    <script>
        buildTable(jsonData2)
        function buildTable(data2) {
            var table = document.getElementById('myTable')
            for (var i = 0; i <= data2.result.length; i++) {
            Object.entries(data2.result).forEach(([name, details]) => {
                //console.log("gotname?", details.data[i]);
                //console.log("whats i", i);
                var row = `<tr>
              <td>${details.data[i].name}</td>
              <td>${details.data[i].user}</td>
              <td>${details.data[i].OS}</td> 
              <td>${details.data[i].sn}</td> 
            </tr>`
                table.innerHTML += row
            });
            }
        };
    </script>
</body>

Answer №2

Find a simple solution to this problem. Also, research indentation techniques and aim to structure your code in a way that is easy for you to comprehend

const table = document.querySelector("#myTable");

const jsonData2 = {
            "result": [{
                "data": [{
                    "user": "admin",
                    "name": "Frank Admin",
                    "OS": "Windows",
                    "sn": "yadayoda123"
                }, {
                    "user": "root",
                    "name": "john root",
                    "OS": "OS/2",
                    "sn": "123-A"
                }]
            }]
        }
        
  let row = ``;
  jsonData2.result[0].data.forEach(object => {
    row = `<tr>
              <td>${object.name}</td>
              <td>${object.user}</td>
              <td>${object.os}</td> 
              <td>${object.sn}</td> 
            </tr>`
    table.innerHTML += row
 })
<table class="table table-striped">
        <tr class="bg-info">
            <th>User</th>
            <th>Name</th>
            <th>OS</th>
            <th>SN</th>
        </tr>
        <tbody id="myTable">
        </tbody>
    </table>

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

Removing HTML elements with jQuery's .html() method

I have a scenario where I am storing the complete content of a <tbody> in a variable, and after some table manipulation, I need to revert back to the original content of the <tbody>. However, when I try to switch back to the original content, j ...

Clicking a button will bring back the component to its assigned ID

How can I dynamically add a component <SaveTask/> to a specific div tag with the id of <div id="saveTask">? When I use this.setState(), it replaces the container and displays only the <SaveTask/> component. However, I want to re ...

Calculating the distinct non-zero elements in two 2D arrays using Python's numpy

Looking to determine the number of values in a 2D array array1 that differ from the values in array2 at the same positions (x, y) and are not equal to 0 in array2, using Numpy. array1 = numpy.array([[1, 2], [3, 0]]) array2 = numpy.array([[1, 2], [0, 3]]) ...

Yii2 HTML helper input must be marked as required

This is the form I have generated using the HTML helper: <div class="row"> <div class='form-group col-lg-6 col-sm-6'> <?= HTML::label('Name:','PropertyContactsNew',['class' => 'control-l ...

What is the best way to update the $scope of a directive from another directive's controller in Angular.js?

One of my directives is responsible for loading a list of events from a service: .directive('appointments', [function () { return { restrict: 'CE', scope: { ngTemplate: '=', ...

Using jQuery to trigger two functions on a click event

I have two functions that I want to apply to the same click event. Initially, I had both of them inside the click function and noticed that while the image toggle worked every time, the show/hide toggle ("optionToggle") only worked the first time. However, ...

I'm curious if there is a method in Vue.js that allows for creating a separator while utilizing v-for, much like the way `Array.join()` or FreeMarker's `<#sep>` functions operate

My goal is to create a list of <span> elements separated by commas using vue.js and v-for. Is there an easy way to achieve this in vue.js? In JavaScript, I would typically use users.join(", "). In FreeMarker templates, you can do some very interes ...

VueJS Unit Testing: Exploring the Content of Attributes- What to Test?

I'm currently facing some challenges with my initial VueJS unit tests using Jest. Although I grasp the concept and have already executed my first set of successful tests, I find myself pondering over the question of "What aspects should I test?" For ...

Express router is unable to process POST requests, resulting in a 404 error

I am having trouble fetching POST requests to my Express router. While my many GET requests work fine, this is my first POST request and it is not functioning correctly. Here is a snippet of my frontend code: export async function postHamster(name, age) ...

Is it possible to have two different actions with two submit buttons in PHP?

Here is my form tag: sample name:register.php page <form id="formElem" name="formElem" action="form10.php" method="post"> <input id="pd" name="pd" type="text" AUTOCOMPLETE=OFF /> <input id="pd1" name="fname" type="text" AUTOCOMPLETE=OFF /& ...

Tips for implementing search suggestions onto an Ajax success event

I have been struggling to implement search suggestion in a text box. I've tried various methods but haven't found the right approach yet. I fetch data (arraylist) from the back end using ajax and return it to jsp as json. Now, I need to add the s ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Having trouble getting the convert-multiple-files npm package to function properly on an Elastic Beanstalk environment running Amazon Linux

Following a successful deployment, I encountered an issue with my file conversion script when attempting to convert files as outlined in the documentation. The script works flawlessly on both a local Windows 10 machine and Ubuntu 20.04 LTS. const { conv ...

Storing multiple field values in a JSON or array format within a column using Laravel

I have a requirement where I need to store information from 3 form fields (name, address, profile_photo) in JSON or array format within a single column. This will allow me to retrieve all the data later on in the view blade. This is how my form is structu ...

What is the best way to transfer information from a child Angular app to a parent non-Angular app

If I have a plain JavaScript parent application with a child Angular application, how can I notify the parent application of any data changes in the child Angular application? The child application is loaded in a div, not in an iframe. ...

Accessing images for a particular user from the Json Placeholder API

Having trouble filtering photos in my Android app using the JsonPlaceholderApi. The issue is that in order to get photos for a specific user, we first have to fetch their albums and then filter the photos based on the album IDs obtained from the album requ ...

Ways to implement bootstrap Modal on a different HTML page

Does anyone know the best way to utilize the Bootstrap modal in a separate HTML page that is generated within the initial HTML page? ...

Preventing opening while closed through the OnClick event

I have the following OnClick function: const [open, setOpen] = useState(true); and onClick={() => setOpen(!open != true)} The goal is to "close when open" and "remain closed if already closed". The current code achieves the second part but not the fir ...

The Right-Click Functionality in SlickGrid

Incorporating SlickGrid into my web application, I am currently contemplating whether to display the context menu based on the specific data row that is right-clicked. However, I am experiencing difficulty in triggering a right-click event as opposed to ...

Utilizing AJAX to retrieve data from a MySQL database upon clicking a button

Hello everyone, I am fairly new to the world of PHP and AJAX, so please bear with me. I am currently attempting to retrieve MySQL results using AJAX. I have made some progress thanks to the information I have gathered from various sources on the internet. ...