14

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.

Michiel
  • 4,160
  • 3
  • 30
  • 42

3 Answers3

26

Array.prototype.map can be used to map one array to another.

var names = employees.map(function(i) {
  return i.name;
});

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

asportnoy
  • 2,218
  • 2
  • 17
  • 31
phylax
  • 2,034
  • 14
  • 13
  • it was an easy one :) - there are more usefull array functions, take a look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype – phylax Apr 12 '14 at 21:07
  • The (cleaner) ES6 sayntax is: `const names = employees.map((i) => i.name)` (Just making [tickietackie's](https://stackoverflow.com/users/9119176/tickietackie) comment to update this old solution more readable) – Cadoiz May 03 '23 at 13:10
2

Array.prototype.map maps one array to another:

var names = employees.map(function (val) {
    return val.name;
});
// ['George', 'Edward', 'Christine', 'Sarah']
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • I marked this answer as a duplicate to [the accepted answer](https://stackoverflow.com/a/23036033/4575793). That was declined because it was answered only a minute later, but I still think, we don't need the same answer twice. – Cadoiz May 03 '23 at 13:04
1

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
  • ?
Cymen
  • 14,079
  • 4
  • 52
  • 72