Make Javascript do List Comprehension

后端 未结 10 1214
情话喂你
情话喂你 2020-12-05 09:05

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 \'

10条回答
  •  生来不讨喜
    2020-12-05 09:50

    Do this in 2020

    const names = collection.map(x => x.name);
    

    MDN | Array.prototype.map()

    Old Answer from 2012

    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(',');
    

提交回复
热议问题