Make Javascript do List Comprehension
generic case using Array.map, requires javascript 1.6 (that means, works on every browser but IE < 9) or with an object augmenting framework like MooTools works on every browser:
var list_of_names = document.getElementsByTagName('input').map(
function(element) { return element.getAttribute('name'); }
);
If dealing with an iterable that doesn't provide map
(such as generators), spread syntax can be used to first create an array:
[...Array(10).keys()].map(x => x * 2 + 3)
Spread syntax will also work with arrays, so if you need to apply map
to any iterable, it's safest to first spread it into a list.
(Note this example also uses an arrow function, which requires ES6 support. Most browser versions support both or neither. IE supports neither, if it itself needs to be supported, though IE has been replaced by Edge for awhile.)
jQuery specific example, works on every browser:
var list_of_names = jQuery.map(jQuery('input'), function(element) { return jQuery(element).attr('name'); });
the other answers using .each
are wrong; not the code itself, but the implementations are sub-optimal.
Edit: there's also Array comprehensions introduced in Javascript 1.7, but this is purely dependant on syntax and cannot be emulated on browsers that lack it natively. This is the closest thing you can get in Javascript to the Python snippet you posted. However that got removed from the language
A list comprehension has a few parts to it.
- Selecting a set of something
- From a set of Something
- Filtered by Something
In JavaScript, as of ES5 (so I think that's supported in IE9+, Chrome and FF) you can use the map
and filter
functions on an array.
You can do this with map and filter:
var list = [1,2,3,4,5].filter(function(x){ return x < 4; })
.map(function(x) { return 'foo ' + x; });
console.log(list); //["foo 1", "foo 2", "foo 3"]
That's about as good as it's going to get without setting up additional methods or using another framework.
As for the specific question...
With jQuery:
$('input').map(function(i, x) { return x.name; });
Without jQuery:
var inputs = [].slice.call(document.getElementsByTagName('input'), 0),
names = inputs.map(function(x) { return x.name; });
[].slice.call()
is just to convert the NodeList
to an Array
.
Those interested in "beautiful" Javascript should probably check out CoffeeScript, a language which compiles to Javascript. It essentially exists because Javascript is missing things like list comprehension.
In particular, Coffeescript's list comprehension is even more flexible than Python's. See the list comprehension docs here.
For instance this code would result in an array of name
attributes of input
elements.
[$(inp).attr('name') for inp in $('input')]
A potential downside however is the resulting Javascript is verbose (and IMHO confusing):
var inp;
[
(function() {
var _i, _len, _ref, _results;
_ref = $('input');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
inp = _ref[_i];
_results.push($(inp).attr('name'));
}
return _results;
})()
];
So, python's list comprehensions actually do two things at once: mapping and filtering. For example:
list_of_names = [x.name for x in list_of_object if x.enabled]
If you just want the mapping part, as your example shows, you can use jQuery's map feature. If you also need filtering you can use jQuery's "grep" feature.