Working with Arrays in Javascript

I am relatively new to the world of JavaScript, so please be patient with me!

Currently, I am retrieving data from an AWS DynamoDB using a lambda script connected to an API gateway.

The JavaScript function on my page successfully issues a GET request for this data. Here is how the retrieved data looks:

{"Items":[{"issue":"my issue","email":"john.doe@example.com","caseDate":1496543576984,"phone":"1234567890","status":"queueing","enterpriseID":"john.doe"},{"issue":"Test issue 02","email":"jane.smith@example.com","caseDate":1496543945585,"phone":"1234567890","status":"queueing","enterpriseID":"jane.smith"}],"Count":2,"ScannedCount":2}

My objective is to dynamically populate a table on a webpage with this data. Below is the code where I attempt to reorder the data items to align with specific column headings:

        var API_URL = 'https://myapi.execute-api.us-west-2.amazonaws.com/dev/cases';
        var table = document.createElement("table");
        
        $(document).ready(function(){
            $.ajax({
                type: 'GET',
                url: API_URL,

                success: function(data){
                    
                    //alert(data);
                    
                    table.setAttribute("id", "myTable");

                    var tableHeader = document.createElement("thead");
                    
                    var headerNames = ["Date", "Enterprise ID", "Client Phone", "Client Email",
                                      "Case Status", "Client Issue"];
                    
                    headerNames.forEach(function(header){
                        var tableHeaderItem = document.createElement("th");
                        var headerText = document.createTextNode(header.toString());
                        
                        tableHeaderItem.appendChild(headerText);
                        tableHeader.appendChild(tableHeaderItem);
                        
                    });

                    table.appendChild(tableHeader);

                    data.Items.forEach(function(queueItem){

                        var myTableRow = document.createElement("tr");
                        myTableRow.setAttribute("id", queueItem.date);
                        
                        var arr1 = $.map(queueItem, function(value, index) {
                            return [value];
                        });

                        const map =[2,5,3,1,4,0]
                        const arr3 = Array.apply(null, Array(map.length))
                        arr3.map((d, i) => arr3[map[i]] = arr1[i]);
                        
                        arr3.forEach(function(item){
                            var tableItem = document.createElement("td");
                            var itemText = document.createTextNode(item);
                            
                            tableItem.appendChild(itemText);
                            myTableRow.appendChild(tableItem);
                        });

                        table.appendChild(myTableRow);
                    })
                    document.getElementById("queueTable").appendChild(table);
                }
            }); 
        });

After retrieving the data and placing it into an array for iteration, I noticed that the order was not correct. Despite trying various solutions online, including the map function, I still couldn't achieve the desired result:

I expect:

mapping["ID","phone","issue","caseDate","status","email"]

But, unfortunately, I'm getting:

mapping["caseDate","ID","phone","email","status","issue"]

This issue has left me frustrated after hours of searching and tinkering. Any assistance would be greatly appreciated!

Answer №1

Why not consider using a data structure like the one below instead of relying on headerNames and internal mappings?

const fields = [
  {name: 'caseDate', header: 'Date'},
  {name: 'issue', header: 'Client Issue'}, 
  {name: 'email', header: 'Client Email'},
  {name: 'phone', header: 'Client Phone'},
  {name: 'status', header: 'Case Status'},
  {name: 'enterpriseID', header: 'Enterprise ID'}
]

You can easily iterate over these to retrieve headers by accessing the header property, and for each row, extract the specified field from the data using item[field.name].

This approach offers a cleaner solution overall.

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

Launch the game within the gaming application

I am looking to incorporate a game within another game... Here's what I mean: Open the app: Pandachii Next, navigate to the 4th button (game pad). When we click on the game icon, I want to launch another game (located below the Pandachii window - c ...

What are the best ways to resolve a Syntax Error at Input issue in Pinescript?

Hello, I am currently working on creating an indicator using chatgpt. Here is the code that was generated for me: study("Volatility Factor", version=5) // Number of bars to look back bars_to_look_back = 20 // Initialize an array to store the ra ...

Creating a button that includes a link and a variable

I'm attempting to create a button that redirects me to another page, but I'm having trouble including a variable in the link. Here's my script: $idSelect[i]="SELECT * FROM times WHERE id=" . $mid[i] . ""; $idResult[i]=mysqli_query($con,$id ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Is it possible to design a Controller and View that can manage the creation of one-to-many objects, specifically a single "container" object along with an unlimited number of "content"

One of the functionalities for users on the website will be the ability to create documents made up of chapters in a one-to-many relationship. Traditionally, this would involve creating separate views for chapter and document creation. How can I develop ...

What is the proper way to cite information from a separate tab without directly copying it?

We are faced with the challenge of managing a large script in a Google Sheet, spanning approximately 1500 lines. Oftentimes, our team members find it helpful to create separate tabs for specific scenes, such as "Scene 1," to make edits more manageable. How ...

Upon loading the page, trigger the controller method by utilizing the information from the query string

Can query string data be retrieved on page load with javascript? Here is how I am attempting to achieve this in my project: The view page displays tabular data. When a button is pressed, it retrieves the row's id and invokes a javascript function. ...

Fetching data from an ajax call and populating a data table

I am facing an issue with ajax and bootstrap table integration. I am making an ajax JSON call using the following method: $(document).ready(function(){ $.ajax({ url: 'php/process.php?method=fetchdata', dataType: 'json' ...

Is it possible to trigger a mouseover event on a background div that is obscured by a foreground tooltip in jQuery?

I created a unique effect where a background div fades in when moused over, followed by the foreground div fading in. However, I encountered an issue where the tooltip ends up "flashing" as the foreground steals focus from the background. For reference, h ...

When using body-parser, req.body may sometimes unexpectedly return undefined

My current project involves creating an API that handles POST requests for user creation. Unfortunately, I'm encountering undefined errors for all the req.body calls. Here's a simplified overview of how my application is structured: User control ...

Error: Attempting to use the map method on currentTodos, which is not

When attempting to send the currentTodos array to Cardhouse, I encountered an issue. I want to pass the currentTodos array from seach-result.component.jsx to the render loop in card-house.component.jsx. Unfortunately, it resulted in an error stating "TypeE ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

Troubleshooting ng-bind-html issue with displaying images loaded using CSS within HTML content

I followed the instructions provided in a related post on the same topic. I used 'ngSanitize' and formatted the HTML content using 'sce.trustAsHtml()', and it rendered correctly when the HTML contained both text and images. However, I e ...

Guide to highlighting rows in v-data-table with a click in Vuetify (version >= 2.0)

In my email management system, I utilize a v-data-table to organize emails. When a user clicks on a row, a popup displaying the email details appears. Desired Feature: I am looking to have the rows marked as "readed" (either bold or not bold) after th ...

Hybrid component that combines static and dynamic elements in Gatsby

The inconsistency in behavior between the site generated by gatsby develop and gatsby build is causing an issue where the site works during development but not when it's in production. An overview of my website: My website is a simple blog-like plat ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

How come the transition does not take effect when removing and adding the class to the same element with the removeClass() and addClass() methods?

Two images are present, with the first one having the class "opacityOne". When a button is clicked, based on the variable index, I want the current image to fade in while the other fades out. It works well when I remove the "opacityOne" class from one ima ...

How can I verify in Javascript that a string contains at least one set of letters and numbers using regex?

I am currently trying to decipher the appropriate regex for identifying a pattern similar to 2d1h30m10s, accepting any valid variation such as 1h, 1h30m, 30m, 10s, or any combination of these. Could regex be the right solution in this scenario? I have bee ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...