Creating an associative array in Javascript by utilizing a for loop

I am attempting to create an array called userRow{} by using:

$('#divResults tr').find('td:nth-child(2)').text();

This will fetch 12 first names from a column in an HTML table, such as John, Dave, and so on.

$('#divResults tr').find('td:nth-child(3)').text();

Similarly, this line retrieves middle names, etc.

Here's what I have tried:

for (var i = 0; i < 12; i++) {
    userRow[i]['jurorFN'] = $('#divResults tr').find('td:nth-child(2)').text();
    userRow[i]['jurorMN'] = $('#divResults tr').find('td:nth-child(3)').text();
    userRow[i]['jurorLN'] = $('#divResults tr').find('td:nth-child(4)').text();
}

However, this code does not output anything to the console.

My goal is to iterate through all the items in the table and, for example, if I alert userRow[1], it should display Dave, M, Johnson (first middle last) and so on.

Answer №1

Make sure to iterate through each $('#divResults tr'):

var userRow = [];
$('#divResults tr').each(function(i) {
    var tds = $(this).find('td');
    userRow[i] = {}
    userRow[i].jurorFN = tds.eq(2).text();
    userRow[i].jurorMN = tds.eq(3).text();
    userRow[i].jurorLN = tds.eq(4).text();
});

Otherwise, you will end up duplicating the first row in the array multiple times


Alternatively, you can use map:

var userRow = $('#divResults tr').map(function() {
    var tds = $(this).find('td');
    return {
        jurorFN: tds.eq(2).text(),
        jurorMN: tds.eq(3).text(),
        jurorLN: tds.eq(4).text()
    };
}).get();

I also made some cosmetic changes:

  • Replaced .find('e:nth-child(n)') with .find('e').eq(n), which optimizes the code by calculating find('e') only once
  • Replaced obj['validIdentifier'] with obj.validIdentifier

Answer №2

In JavaScript, there is no direct equivalent to an associative array; instead, objects are accessed in array style. It is recommended to define an object before assigning data to it, like so: userRow[i] = {}

I find the remaining code to be somewhat ambiguous...

Answer №3

If you take a look at the provided code snippet, you can try the following approach:

let userList = [];
for ( let i=0; i < 12; i++) {
  let jurorFN = $('#divResults tr').find('td:nth-child(2)').text();
  let jurorMN = $('#divResults tr').find('td:nth-child(3)').text();
  let jurorLN = $('#divResults tr').find('td:nth-child(4)').text();
  let fullName = jurorFN + ' ' + jurorMN + ' ' + jurorLN;
  userList.push(fullName);
}
console.log(userList[0]); // from userList[0] to userList[11]

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

Development versions of npm libraries

Lately, I came across a library called react-3d-components that offers some d3 react components with basic charts. It's an impressive collection of components. However, when trying to access the source code due to incomplete documentation, I found my ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

When submitting an Asp net mvc Form, some fields may not be posted as expected

I'm facing an issue with my ASP.NET MVC application form. Some fields that should be posted are missing, and I can't figure out why. <form id="FormRegistroUsuario" action="/Account/AdminSecurityUserAccountAdd"> <fieldset> ...

What steps should I follow to create a large Angular single page application using ASP.NET MVC?

After gaining some experience with AngularJS on a small project, I am now ready to tackle a larger application. My plan is to create a single-page application using asp.net, making WebAPI calls and loading AngularJS views. However, I am unsure about how ...

Create a more concise JavaScript function for updating MongoDB using if/else statements

Can this function be optimized for efficiency and readability? I'm not a fan of the repetitive if/else structure, especially considering that it's only setting 'status.edited': false when method equals 'reset'. Otherwise, it s ...

Node.js command-line interface for chat application

Can someone help me figure out the best method for creating a command line interface chat app using nodejs? I'm considering using http and possibly phantomjs to display it in the terminal, but I have a feeling there's a more efficient approach. A ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...

Stream-Awesome #12: The Return of Duplexer in Nodesville

For days, I've been attempting different methods to solve this exercise. It's frustrating because no matter what I try, I keep encountering a "write after end" error. But here's the thing - I'm using the "end" event and not writing anyt ...

Discover the way to utilize the java enum toString() function in jQuery

In my Java Enum class called NciTaskType, I have defined two tasks: Pnd Review Woli and Osp Planning. public enum NciTaskType { PndReviewWoli, // 0 OspPlanning, // 1 ; @Override public String toString() { switch (this) ...

How to interact with a C# List using JavaScript

Our internship project entails creating a business application using Unity WebGL. However, we're facing a challenge when it comes to retrieving a list from C# to populate a Select element on our webpage. We've successfully communicated and retrie ...

transfer an image file to a php script using ajax

Having just started, my goal is to upload an image and send it to a server for insertion into a database. Initially, all I want to do is echo the file name that I will be sending. However, I am encountering issues with this process, as I keep receiving noi ...

The success function of the Ajax request remains untouched by the response

My ajax call isn't triggering the success:function(resp){ ...} Despite receiving a response status of 200 and a non-null Json response. This is my ajax setup: $.ajax({ url: '/url/', type: 'GET', data: { pass_ ...

gdal.vectorTranslate causing output files to be void

Attempting to use gdal-async in nodejs for converting vector files from geojson to dxf. const dsGeoJSON2 = gdal.open('./upload2/objects.geojson'); const out2 = gdal.vectorTranslate('./upload2/objects.dxf', dsGeoJSON2, ['-f', ...

Utilize HTML5 to enable fullscreen functionality for embedded SWF files

I have implemented a function that handles the click event of a button to toggle a DOM element into fullscreen mode. The function works well, but I am facing an issue when there is another div containing a swf inside the main div. var elem = document.getE ...

Sinon respects my intern functions during testing in ExpressJS

At the moment, I am working on incorporating sinon stubs into my express routes. However, I am facing an issue where my functions are not being replaced as expected. I would like my test to send a request to my login route and have it call a fake function ...

What is the best way to combine objects that share the same id?

View Image: Displaying Image POST ID's https://i.stack.imgur.com/JO5OF.png I attempted to resolve this using jQuery each, but I am uncertain about the next steps. Check out my Code: jQuery(document).ready(function($) { var data, exampleData, , ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

What could be causing the ajax request to not go through?

Check out this function I created that triggers an event when any inputs in an HTML form are changed. Function Snippet: function customEvent(form, element) { var timer; $(element).keyup(function () { clearTimeout(timer); if ($(ele ...