Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Lets say I have an array of objects:

var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}

Is there an array function that will allow me to get one property as an array, for example:

namesArray = employees.reduceToProperty('name'); // none existent function i made up!

// should return ["George","Edward","Christine","Sarah"]

I know how get the desired result with a loop, I am just hoping for an array function or combination of functions exist that can do this in one line.

share|improve this question

marked as duplicate by Felix Kling, zzzzBov, daniel, Donal Fellows, Farid Nouri Neshat Apr 13 '14 at 15:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
and stackoverflow.com/q/19590865/218196 – Felix Kling Apr 12 '14 at 21:42
up vote 6 down vote accepted
var names = employees.map(function(i) {
  return i.name;
});

names is now an array containing the name-properties of the objects.

share|improve this answer
    
Thanks phylax, this is exactly what i meant. – Michiel Apr 12 '14 at 21:03
    
it was an easy one :) - there are more usefull array functions, take a look: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – phylax Apr 12 '14 at 21:07

Array.prototype.map maps one array to another:

var names = employees.map(function (val) {
    return val.name;
});
// ['George', 'Edward', 'Christine', 'Sarah']
share|improve this answer

If you find yourself doing this frequently, you might consider using pluck from Underscore/Lo-Dash:

var listOfPropertyNames = _.pluck(list, 'propertyName');

If you don't want to do include a library, it is of course possible to write your own pluck for use on your code base:

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

And running it:

pluck([{name: 'a'}, {name: 'b'}], 'name');
["a", "b"]

You'll have to decide how to handle the edge cases like:

  • object in the list not having the property
  • an undefined being in the list
  • ?
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.