Reputation:
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
Upvotes: 0
Views: 409
Reputation: 97691
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:
.find('e:nth-child(n)')
with .find('e').eq(n)
, since that allows find('e')
to be calculated once and reusedobj['validIdentifier']
with obj.validIdentifier
Upvotes: 1
Reputation: 63587
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]
Upvotes: 0
Reputation: 2495
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...
Upvotes: 0