Search code examples
javascriptpythonjquerylist-comprehensionlanguage-comparisons

Make Javascript do List Comprehension


What is the cleanest way to make Javascript do something like Python's list comprehension?

In Python if I have a list of objects whose name's I want to 'pull out' I would do this...

list_of_names = [x.name for x in list_of_objects]

In javascript I don't really see a more 'beautiful' way of doing that other than just using a for loop construct.

FYI: I'm using jQuery; maybe it has some nifty feature that makes this possible?

More specifically, say I use a jQuery selector like $('input') to get all input elements, how would I most cleanly create an array of all the name attributes for each of these input elements--i.e., all of the $('input').attr('name') strings in an array?


Solution

  • 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