Equivalent of Underscore.js _.pluck in jQuery

后端 未结 4 795
闹比i
闹比i 2020-12-30 00:38

Does anyone know of a \'pluck\' plugin that matches the underscore array method?

pluck_.pluck(list, propertyName) 

A convenient version of

相关标签:
4条回答
  • 2020-12-30 00:44

    It's quite simple to implement this functionality yourself:

    function pluck(originalArr, prop) {
        var newArr = [];
        for(var i = 0; i < originalArr.length; i++) {
            newArr[i] = originalArr[i][prop];
        }
        return newArr;
    }
    

    All it does is iterate over the elements of the original array (each of which is an object), get the property you specify from that object, and place it in a new array.

    0 讨论(0)
  • 2020-12-30 00:48

    just write your own

    $.pluck = function(arr, key) { 
        return $.map(arr, function(e) { return e[key]; }) 
    }
    
    0 讨论(0)
  • 2020-12-30 00:51

    You can do it with an expression;

    var arr = $.map(stooges, function(o) { return o["name"]; })
    
    0 讨论(0)
  • 2020-12-30 01:04

    In simple case:

    var arr = stooges.map(function(v) { return v.name; });
    

    More generalized:

    function pluck(list, propertyName) {
        return list.map(function (v) { return v[propertyName]; })
    }
    

    But, IMHO, you should not implement it as tool function, but use the simple case always.

    2018 update:

    var arr = stooges.map(({ name }) => name);
    
    0 讨论(0)
提交回复
热议问题