Developing a table with JavaScript by parsing JSON data

Starting off, I am relatively new to working with JavaScript. Recently, I attempted to generate a table using data from a JSON file. After researching and following some tutorials, I successfully displayed the table on a web browser. However, I noticed that the arrays in the JSON file were always sorted and only allowed unique values. Here is an example of the JSON data:

var json = {
            "data": [
                {
                    "number": "13",
                    "position": "GK",
                    "name": "John"
                },
                {
                    "number": "2",
                    "position": "CB",
                    "name": "Bill"
                },
                {
                    "number": "26",
                    "position": "CB",
                    "name": "Nick"
                }

When I input this data into my table, it appears like this:

| Number | Position | Name |
|   2    |    GK    | John |
|   13   |    CB    | Bill |
|   26   |undefined | Nick |

As you can see, the numbers in the JSON file do not correspond correctly with the names, and they are sorted incorrectly. For instance, John should have number 13, not 2. Additionally, it does not allow duplicate values - there are 2 entries for CB position, but only one is displayed while the other shows as undefined.

I have included the code snippet below:

     JSONDataLouder = {
     getPlayers: function(json) {
      var object = {
        "number": {}
        , "position": {}
        , "name": {}
    };

    var personData = null; 
    for (var i = 0; i < json.data.length; i++) {
        personData = json.data[i];
        object.number[personData.number] = 1;
        object.position[personData.position] = 1;
        object.name[personData.name] = 1;
    }

    var u = {
        "number": []
        , "position": []
        , "name": []
    };

    for(var k in object.number) u.number.push(k);
    for(var k in object.position) u.position.push(k);
    for(var k in object.name) u.name.push(k);


    return u;

}

,getTable: function(json) {

    var obj = this.getPlayers(json);

    var number = obj.number;
    var position = obj.position;
    var name = obj.name;

    var table = this.createTable();


    var headerRow = table.insertRow();
    headerRow.insertCell().innerHTML = "Number";
    headerRow.insertCell().innerHTML = "Position";
    headerRow.insertCell().innerHTML = "Name"


    for (var i = 0; i < number.length; i++) {
        var secondRow = table.insertRow();
        secondRow.style.textAlign="center";
        secondRow.insertCell().innerHTML = number[i];
        secondRow.insertCell().innerHTML = position[i];
        secondRow.insertCell().innerHTML = name[i];

    }

    return table;
}


,render: function(mainDiv) {

    $( mainDiv ).empty();
    var json = {
        "data": [
            {
                "number": "13",
                "position": "GK",
                "name": "John"
            },
            {
                "number": "2",
                "position": "CB",
                "name": "Bill"
            },
            {
                "number": "26",
                "position": "CB",
                "name": "Nick"
            }

It seems I may have erred in understanding how to push objects into an array, despite attempting multiple fixes. Any assistance or insight would be greatly appreciated. Thank you for taking the time to help.

Answer №1

It seems like the issue you're encountering is related to the unordered nature of hashes in JavaScript. When using for(var k in object.number), it's not guaranteed that each number will be retrieved in the same order they were inputted.

On the other hand, arrays maintain their order.

You may not even need the object variable. Instead, you can simplify your code like this:

JSONDataLouder = {
  getPlayers: function(json) {

  var u = {
    "number": [],
    "position": [],
    "name": []
  };

  var personData; 
  for (var i = 0; i < json.data.length; i++) {
    personData = json.data[i];
    u.number.push(personData.number);
    u.position.push(personData.position);
    u.name.push(personData.name);
  }

  return u;
}

Answer №2

When experimenting with different test data, you may encounter even more surprising outcomes. While there are various issues within the code, one major setback seems to be the mix-up of data structures. Instead of focusing solely on the table setup, consider first establishing a suitable intermediate data structure, perhaps resembling a two-dimensional array in practice.

An interesting point to note is that an intermediate structure may not be necessary at all. The JSON.data already contains an array which you transform into a different format within your code.

To simplify the table generation process, here's a snippet that captures the essence while bypassing some details:

var json = {
    "data": [
        {
            "number": "13",
            "position": "GK",
            "name": "John"
        },
        {
            "number": "2",
            "position": "CB",
            "name": "Bill"
        },
        {
            "number": "26",
            "position": "CB",
            "name": "Nick"
        }
    ]
};


function objToTable(obj) {
    var data = obj.data;
    var output = '<table>';
    for (var i = 0; i < data.length; i++) {
        output += '<tr>';
        output += '<td>' + data[i].number + '</td>';
        output += '<td>' + data[i].position + '</td>';
        output += '<td>' + data[i].name + '</td>';
        output += '</tr>\n'; // included newline for better readability
    }
    output += '</table>';
    return output;
}


console.log(objToTable(json));

Answer №3

Maybe this solution could be of assistance to you

    var data = {
      "items": [
        {
          "number": "13",
          "position": "GK",
          "name": "John"
        },
        {
          "number": "2",
          "position": "CB",
          "name": "Bill"
        },
        {
          "number": "26",
          "position": "CB",
          "name": "Nick"
        }]
      };
        
        console.log('|  Number  |  Position  |  Name  |');

        $.each(data.items, function(index, element)
        {
         
             console.log(element.number + '|' + element.position + '|' + element.name + '|');
        
        });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...

Creating a Client-side Web Application with Node.js

As I search for a versatile solution to bundle an HTML5 web application (without server dependencies) into a single executable app using node.js and the Linux terminal on Ubuntu, I have experimented with tools like wkpdftohtml and phantomjs. However, these ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

Having trouble generating package.json with npm init on my Mac

Every time I attempt to generate a package.json file by using the command npm init, I encounter the following issue: npm http GET https://registry.npmjs.org/init npm http 304 https://registry.npmjs.org/init npm http GET https://registry.npmjs.org/daemon n ...

Customizing the jQuery Datepicker to only allow a predefined set of dates

I am looking for assistance regarding the jQuery datepicker. I have an array of dates and I need to disable all dates except for the ones in this specific array. Currently, the code I have does the opposite of what I need. I generate the array of dates in ...

What is the best way to use jQuery to fill a dropdown menu with options from a JSON object?

Looking to populate a dropdown box #dropdown with values from a json object stored in a JavaScript string variable. How can I access each element as value/label pairs and insert them into the dropdown? The structure of the json string is as follows: [{"n ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

Scrolling behavior in two columns with sticky positioning

Both columns have varying heights, with the left sometimes higher than the right. I want them to start scrolling down simultaneously, but when the shorter column's content ends, it should stick to the bottom of the viewport and "wait" until the taller ...

Step-by-step guide on building an engaging Donut chart using jQuery

After spending several hours working on it, I'm struggling to draw my donut graph with JavaScript. Can anyone provide a solution? I am looking for a way to add 25% when one checkbox is selected and +25% when two checkboxes are selected. Thank you in a ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

Steps for embedding the code into your website

I'm facing an issue with integrating a .jsx file into my website. I tried testing it on a single-page demo site, but nothing is showing up. Can someone guide me through the steps to successfully integrate it onto my site? I've also attached the . ...

Determine the position and quantity of elements in jQuery by comparing their IDs with the current page or element

Looking to retrieve the n (zero based) position of an element by matching the page and element ID... Let's use an example (Assume the current page ID is 488); <ul id="work-grid"> <li id="item-486" class="work-item"><!--/content--& ...

Transferring elements from one array to multiple arrays

I have been working with the basics of JavaScript arrays and here is my code snippet: let arr = ['students', 'exams', [{'sub1':80, 'sub2':60},{'grade_sub1':'A', 'grade_sub2':'B&apos ...

Issue with displaying jqplot in a jQuery page

Currently, I'm utilizing jqmobile pages for switching between various pages in an html5 application. One of these pages features a jqplot chart. Below is the code snippet: <div data-role="page" id="page-two" data-title="Page 2"> &l ...

Encountering crashes when trying to map JSON data onto React components

I have created a menu items application that displays products from a JSON file. When an item is clicked, it shows some modifiers for that item. Everything works well until certain categories or items are clicked, causing the application to crash. To test ...