collections-pluck1

by shan10213223

JavaScript

var _ = {};
// _.pluck(collection, propertyName)
// A convenient version of what is perhaps the most common use-case for map:
// given an array of objects (collection), iterates over each element
// in the collection, and returns an array with all the values
// corresponding to the property indicated by propertyName.
_.pluck = function (collection, propertyName) {
  let results = [];
  let key = propertyName;
  //console.log(key);
  for (let i=0; i<collection.length; i++) {
    //console.log(collection[i][key]);
    //console.log(collection.keys());
    results.push(collection[i][key]);
    
  }
  return results;
};

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
let test1 = _.pluck(stooges, 'name');
//=> ["moe", "larry", "curly"]
console.log(test1);