Speed up development with full-stack environments for every branch.

Learn More

How to pluck values from array with underscore.js [jQuery and JavaScript]

Forked from How to filter an array with underscore.js.

1649 Runs 48395 Views 4336 Copies


lribeiro 90

published 4 years ago

// _.pluck(list, propertyName) 
//  A convenient version of what is perhaps the most common use-case for map: 
//  - extracting a list of property values.

// retrieve all the values of the property name 
names = function(array){
    return _.pluck(array, "name");

// retrieve all the ages from an array of objects
ages = function(array){
  return _.pluck(array,"age");

// retrieve all hair colors 
// (when an object doesnt have the hair property, null will be returned as value)
hair = function(array){
  return _.pluck(array,"hair");

//wait for page to load (need to make sure the placeholders are already positioned)
  // starting data
  var users = [
    {name: "Luís", age: 14},
    {name: "Martin", age: 56, hair: "black"}
  // get all the names of the users
  var namesResult = names(users);
  // get all the ages
  var agesResult = ages(users);
  // get all hair colors
  var hairResult = hair(users);

  // display the results in our html page

// Helper method to display results our html page (each time its called creates a new row)
displayValues = function(source,data,result){
  var html  = ("<tr><td><pre>" + source.toString() + "</pre></td>");
  html += "<td class='big'> + </td>";
  html += "<td><pre>" + JSON.stringify(data,null,4) +"</pre></td>";
  html += "<td class='big'> = </td>";
  html += "<td>" + JSON.stringify(result) + "</td></tr>";
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).