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

Is Jacksson up to the task of managing enums?

Imagine having an enum type called Gender. @Enumerated(EnumType.STRING) private Gender gender; Can the Jackson JSON parser successfully assign a value to this field from a JSON string? ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

Give me an example of converting a MultiDimensional JSON Array into a data class in Kotlin

I received a JSON response that I will refer to as JSON_A: { "result": [ { "id": 1, "vendorTitle": "erlangga", "vendor_id": "178", "userstat": true } ...

Combining element.scrollIntoView and scroll listener for smooth scrolling by using JavaScript

Can element.scrollIntoView and a "scroll" event listener be used simultaneously? I'm trying to create code that checks if the user has scrolled past a certain element, and if so, automatically scrolls smoothly to the next section. I attempted to achi ...

Harvesting information from an HTML table

I have a table displaying the following values: turn-right Go straight turn-left How can I extract only the 2nd value, "Go straight"? Here is the code snippet I tried: var text = $('#personDataTable tr:first td:first').text(); The code above ...

Using AJAX to dynamically load Javascript

I came across this interesting code snippet: <script type="text/javascript" language="javascript"> $(function(){ $(window).hashchange( function(){ window.scrollTo(0,0); var hash = location.hash; if (hash == "") { hash="#main"; } ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

Utilizing Think ORM seamlessly across multiple files without the need to repeatedly establish a connection to the

I'm facing a situation where I have numerous models for thinky, and in each file I am required to create a new object for thinky and connect it multiple times due to the high number of models. var dbconfig = require('../config/config.js')[& ...

The array is being initialized with a higher number of elements than prescribed

Python: list = [1, 2, 3, 4, 5, 6, 7] print(list) When executed, it displays the list of integers: [1, 2, 3, 4, 5, 6, 7] The output accurately reflects the values stored in the list without any additional information. ...

Tips on optimizing a setTimeout script for seamless integration with an HTML form

Here is the script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function addToCart() { document.getElementById("msgs-box").innerHTML = "Item added to cart s ...

What is the best way to configure a metered subscription plan on Stripe that invoices annually but bills extra fees for overage on a monthly basis

I'm in the process of setting up a subscription system on stripe that includes a plan with 5000 monthly credits for a flat $299 yearly fee. My goal is to charge customers who exceed their monthly credit limit by the end of each month. For example, if ...

Utilizing Spring's Rest Service in Version 4.x

Despite encountering numerous inquiries on the subject, none have proven helpful to me. I'm attempting to launch a basic REST service, but no matter what I try, it just won't work. My initial approach was to set up a REST controller like this: ...

What specific types of errors is this try-catch block designed to catch and manage?

// This function establishes a connection to MongoDB using Mongoose const connectToDatabase = (url) => { return mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Conn ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

Passing JSON information using JQuery's ajax.post to PHP

When sending data to a PHP file via AJAX using POST, I initially had success submitting strings. However, when attempting to submit my JS Object with JSON and decode it on the PHP side, I encountered issues. Although the console shows that my data is bein ...

A method for utilizing history.goBack in linked tabs while preventing the user from reverting to the previously selected tab

In my application, I have a settings modal that contains tabs which act as links to different paths. When the user clicks on the background outside of the modal, it triggers the history.goBack function. However, I noticed that if the user has already click ...

Make sure that a specific script is loaded prior to another script

I'm struggling to understand how scripts are loaded on a page. I have jQuery plugins that rely on other scripts. Specifically, I am using the timeago jQuery plugin. I have loaded these scripts in the head in the following order: <script src="< ...

Parsing JSON responses in Titanium mobile

In an attempt to extract the DishName from a json string returned by my php api, I am facing some difficulties. The json string appears as follows: ["Spicy.com Specials",{"CatID":31,"CatName":"Spicy.com Specials","DishName":"Kashmiri Chicken","DishID":5 ...

Executing a background.js function in response to an event trigger within the active tab in a Chrome extension

I am facing an issue where I am getting an error saying "resetTime is not defined" when running the code below. I have tried passing the function as an argument, but that did not solve the problem. Do I need to come up with a new logic to reset the time ...

Reactive Form value is not displaying in view because of FormControlName issue

I have successfully retrieved data from the database and need to pre-fill an update form with preset values. The issue I am facing is that when I add FormControlName to the input field, it removes the preset values. I have tried using setValue and patchV ...