0

I'm trying to build an array userRow{} using

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

which would return 12 first names, grabbing from a html table column Ex. John, Dave, ect..

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

returns middle names, ect.

what I've 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();
        }

which won't console.log anything

I want it to loop all of the items on the table and have it so if I alert userRow[1] it would output Dave, M, Johnson (first middle last) ect

3 Answers 3

1

You need to iterate over 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, all you're doing is duplicating the first row into the array 12 times


Or with 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();

Other cosmetic changes I made:

  • Replace .find('e:nth-child(n)') with .find('e').eq(n), since that allows find('e') to be calculated once and reused
  • Replace obj['validIdentifier'] with obj.validIdentifier
Sign up to request clarification or add additional context in comments.

2 Comments

OP wants the output as 'Dave, M, Johnson' so having them as separate keys in an array element is no good.
Thank you, that was what I was trying to achieve.
0

In js there is not something like associative array, only objects accessed in array style. I think that you should define object before you put some date into: userRow[i] = {}

The rest of code is unclear for me...

Comments

0

Just going purely on the code you've provided, give this a go:

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

3 Comments

Where'd :has(:checkbox:not(:checked)) come from?
Looks like it was edited out of the original question after I posted my code. Edited.
Sorry, it was accidentally left in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.