Iain Freestone

❓ JavaScript Q & A No. 3 - How do I pull a property from each value when iterating over an array of Objects?

May 31, 2020

Use case

Take an array of user objects and return an array containing all the users ages.

Answser

const usersArray = [
  { user: "Iain", age: "39" },
  { user: "Matthew", age: "45" },
  { user: "Jessica", age: "35" },
];

const returnUserProperty = (prop) =>
  usersArray.map((item) => {
    return item[prop];
  });

// Plain JavaScript
usersArray.map((item) => item.age);

// Ramda
R.pluck("age", usersArray);

//Lodash
_.map(usersArray, "age");

// Result
// [ '39', '45', '35' ]

Reference

Methods used

JavaScript - Array.prototype.map

Ramda - pluck

Lodash - map