Nate Reed Nate Reed - 2 months ago 5
Javascript Question

Why can't I use map to collect the properties of an array of objects in Javascript?

I have a collection of th's that I want to get the textContent property from and put in a list. map() does not work as expected:

table_headers = $("#careerStats table thead tr th");
headers.map(function(obj) {return(obj.textContent);});
[]


When I write an iterative version of this, I am able to get an array of values as I expected:

values = [];
for (i=0; i<table_headers.length; i++) {
values.push(table_headers[i].textContent);
}

values
["Year", "Team", "LG", "W", "L", "ERA", "G", "GS", "CG", "SHO", "SV", "SVO", "IP", "H", "R", "ER", "HR", "HB", "BB", "IBB", "SO", "AVG", "WHIP", "GO/AO", "Year", "Team", "LG", "W", "L", "ERA", "G", "GS", "CG", "SHO", "SV", "SVO", "IP", "H", "R", "ER", "HR", "HB", "BB", "IBB", "SO", "AVG", "WHIP", "GO/AO"]


I must be misunderstanding something about Javascript prototypes and/or map().

Answer

You are not using JavaScript's map() - it's jQuery's map() which behaves in a different fashion: jQuery's map has a following signature:

$(selector).map(function (index, value) { ... })

You have to use the second arguments to access selected element:

table_headers.map(function(idx, obj) {return(obj.textContent);});

There is another difference between jQuery's map and JS's map. jQuery returns a new wrapper, not a plain array. To get the underlying array, you can access it using get:

mapped_table_headers.get()
Comments