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 \'
const names = collection.map(x => x.name);
MDN | Array.prototype.map()
Yeah—I miss list comprehensions too.
Here's an answer that's slightly less verbose than @gonchuki's answer and converts it into an actual array, instead of an object type.
var list_of_names = $('input').map(function() {
return $(this).attr('name');
}).toArray();
A use case of this is taking all checked checkboxes and joining them into the hash of the URL, like so:
window.location.hash = $('input:checked').map(function() {
return $(this).attr('id');
}).toArray().join(',');