Equivalent of Underscore _.pluck in pure JavaScript

前端 未结 6 1297
旧巷少年郎
旧巷少年郎 2020-12-14 07:05

I\'m trying to recreate the Underscore pluck function using pure JS. However, I keep getting an array of undefineds being returned, instead of the actual values from the pr

6条回答
  •  不知归路
    2020-12-14 08:03

    How about a reduce:

    $.pluck = function(arr, key) { 
        return arr.reduce(function(p, v) { 
          return p.concat(v[key]); 
        }, []); 
    }
    
    var people = [
      { name: 'James', age: 26 }, 
      { name: 'Fred', age: 56 }
    ];
    
    $.pluck(people, 'age');
    => [26, 56]
    
    $.pluck(people, 'name');
    => ['James', 'Fred']
    

提交回复
热议问题