Javascript Array of objects get single value [duplicate]

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.

Answers:

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

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

Answer

Array.prototype.map maps one array to another:

var names = employees.map(function (val) {
    return val.name;
});
// ['George', 'Edward', 'Christine', 'Sarah']
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
  • ?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.