Javascript - Accessing a specific element in an array using a variable

I am currently developing a webpage that interacts with a CGI backend. While the CGI backend is functioning well, my limited knowledge of JavaScript is making it hard for me to manage the results retrieved from AJAX JSON requests.

Here's what I have:

A JavaScript function sends queries to the CGI.

The CGI responds with a JSON array.

    {
    "ARRAY": [
        {
            "line": "1",
            "numbers": "12321",
            "var": "12321",
            "var2": "12321"
        },
        {
            "line": "2",
            "numbers": "-1",
            "var": "12320",
            "var2": "6160"
        }
    ]
}

The 'line', 'numbers', 'var', and 'var2' data must be displayed in separate cells of a table.

<table>
<tr>
<th>line</th><th>numbers</th><th>var</th><th>var2</th>
</tr>
<tr>
<td>ARRAY[0].line</td><td>ARRAY[0].numbers</td><td>ARRAY[0].var</td><td>ARRAY[0].var2</td>
</tr>
<tr>
<td>ARRAY[1].line</td><td>ARRAY[1].numbers</td><td>ARRAY[1].var</td><td>ARRAY[1].var2</td>
</tr>
</table>

My current issue is:

I don't know beforehand how many objects will be stored inside the array. In this example, there are 2, but there could be up to 20 or more. I am open to modifying my JSON structure if necessary. How can I create a loop that iterates through all the objects in the array?

Answer №1

There are a few methods available for iterating through an array. One common way is to use a simple for loop like this:

for (var i = 0, len = ARRAY.length; i < len; i++) {
    //Build table row using ARRAY[i].line, etc
}

Another option is to use Array.forEach, which is supported in newer browsers and can be polyfilled for older versions as well:

ARRAY.forEach(function(idx, elt) {
    //Build table row using elt.line, etc
});

If you prefer using jQuery, there's also the $.each function:

$.each(ARRAY, function(idx, elt) {
    //Build table row using elt.line, etc
});

For a more detailed example utilizing the jQuery library, consider the following:

var url = '/cgi-bin/your_script_name.cgi';
var html = '<table><tr><th>line</th><th>numbers</th><th>var</th><th>var2</th></tr>';
$.get(url, function(response) {
    $.each(response.ARRAY, function(idx, elt) {
        html += '<tr><td>' + elt.line + '</td><td>' + elt.numbers + '</td><td>' + elt.var + '</td><td>' + elt.var2 + '</td></tr>';
    });
    html += '</table>';
    $('#target-element').html(html);
});

In this example, the generated table will be inserted into an element with the id target-element, and the cgi script URL is assumed to be located at /cgi-bin/your_script_name.cgi. If jQuery is not an option, you'll have to handle the AJAX request manually using XMLHttpRequest and parsing the response appropriately. I hope this explanation was helpful.

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

Leveraging a global array in a PHP multi-page form

My goal is to develop a php multipage form, but I'm facing challenges with using $_SESSION variables to store and retrieve data when moving between pages. I've considered using a custom global array (e.g. GLOBAL $data; $data = array();) to store ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Forming a distinct array from a collection of objects

Describing demoList: demoList = [ { id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ2 ...

Decoding JSON Data in Google Web Toolkit

In our development, we have utilized the GWT Platform along with GWTP client and rest web services within a GUICE container. The invocation of rest services from the GWT client is achieved using JSONPRequestbuilder. I am curious to discover the most effec ...

Guide on exporting a reducer from a Node module built on React Redux

I am currently working on a project that requires importing a component from an external node module. Both the project and the component utilize React and Redux, and I intend for them to share the same store. Below is a snippet of the reducer code for the ...

Passing the reference of every row in a matrix to a function

Currently, I am diving into the world of memory allocation in C programming. My goal is to construct a matrix of size [10][20] using malloc. Each row in this matrix needs to be passed through a function for processing. Should I only send the pointer of eac ...

Creating a dynamic Bootstrap 5 carousel with active class on the first item and indicators

I am curious to know how to create a dynamic Bootstrap 5 carousel. Specifically, I want to know how to display indicators dynamically and add an active class to the first item of the carousel. In Bootstrap 4, it is done in the following way: $('#main ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Combining data from an element in a list with a state object in Redux

While experimenting with redux and reactjs, I came across an interesting scenario: I have a collection of items const items = [ {id: 0, name: 'one'}, {id: 1, name: 'two'}, {id: 2, name: 'three'} ] const itemsWithTheFl ...

The issue with AngularJS array filtering remains unresolved

How can I get this filter to function properly? <div ng-repeat="rvs in reviews | filter:{ Name:'{{ r.Name }}' }"> {{ rvs.Name }} </div> 'r.Name' is retrieved from another array "r in restaurants" However, instead of usin ...

Convert HTML table to CSV format while retaining merged rows and columns

I have a complex HTML table with rows and columns spanning different sections. I am looking for a way to export this table to a CSV file with just a click of a button.https://i.sstatic.net/OOPgg.png Here is the code snippet for the table, <table clas ...

Extract the complete HTML information from the weather website

Currently, I am attempting to retrieve weather data from the following website: using this code snippet: try { int i = 0; if (googlefirst3.startsWith("http")) { Document document = Jsoup.connect("https ...

Any tips or hacks for successfully implementing vw resizing on the :before pseudo-element in webkit browsers?

When using vw sizes on webkit browsers, a well-known bug can occur where they do not update when the window is resized. The typical workaround for this issue has been to employ javascript to force a redraw of the element by reassigning the z-index upon res ...

Can you explain the return value of array.find() in Typescript or Java script?

In my Typescript code, I have the following line: const addressFound: AddressPrimary = <AddressPrimary>(this.addressArray.find(addr => addr.id === id)); The AddressPrimary class contains various variables such as id: number, city: number, and oth ...

Tips for toggling a menu by clicking a link

I have a Navbar component with a hamburger menu. When the hamburger menu is clicked, I want to display the menu component, which is separate. To achieve this, I passed data through props and made it work. Now, I want the menu to close when clicking outsi ...

What is preventing me from accessing arguments.callee within this function in sloppy mode?

In attempting to retrieve the arguments.callee property in the following basic function, I encountered an error preventing me from doing so. function foo(a = 50, b) { console.log(arguments.callee); } foo(10, 50); Why is this issue occurring? It appe ...

What is the best way to release a collection of string pointers in C++?

Feel free to provide any comments or feedback on the code! This function takes a string as input and creates an array of string pointers, where each string starts with a specific letter. I'm encountering an error in the function free_string() and I& ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

Modify the input field in the datepicker to resemble a button

How can I transform an input field into a button that looks like this https://i.sstatic.net/BDk5C.png rather than this https://i.sstatic.net/UdXoE.png? The simple switch of tag names doesn't seem to work. Any suggestions on how to achieve this? cla ...