Explain Codes LogoExplain Codes Logo

From an array of objects, extract value of a property as array

javascript
map-function
performance
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 19, 2024
TLDR

Here's how to extract an array of property values using map().

const objArray = [{ prop: 'A' }, { prop: 'B' }]; const propArray = objArray.map(o => o.prop); // Yields ['A', 'B']

Efficiency and alternatives

Working with a large array? Though map() is a front-runner for elegance, an indexed for loop could give you a slight performance leverage in some situations. That’s raw performance for you!

let propArray = []; for (let i = 0; i < objArray.length; i++) { propArray.push(objArray[i].prop); // Shoving props into a new array! }

ES6 offers an even better soultion with the for..of loop. It brings the best of both worlds - performance and readability:

let propArray = []; for (const obj of objArray) { propArray.push(obj.prop); // "Gimme your props!" }

And if you're coding in style or handling more complex situations, libraries like Lodash or Ramda have got your back:

// Extracting props like a boss with Lodash const propArray = _.map(objArray, 'prop'); // Ramda makes prop extraction a breeze const propArray = R.pluck('prop')(objArray);

Understanding map()

The map() function works well with arrow functions, making your code cleaner. Single-expression arrow functions don't even require an explicit return. Forget about verbosity!

const propArray = objArray.map(obj => obj.prop); // "Hand over your props!"

ES6 permits destructuring within the map() callback. It’s like picking the chocolate chips out of a cookie:

const propArray = objArray.map(({ prop }) => prop); // Just the chips please!

Dealing with nested properties? Don’t sweat it, map() has you covered:

const orchestraWithDetails = [{ musician: 'Violinist', instrument: { name: 'Violin' } }]; const instruments = orchestraWithDetails.map(({ instrument }) => instrument.name); // Navigating the nested world!

When you need to extract multiple properties, just use map() again!

const moreProps = objArray.map(o => ({ propName: o.prop, propLength: o.prop.length, // Because size does matter! 😄 }));

Handling edge cases and errors

Remember to ensure your object has the property you're extracting. If you are working with nullable objects, filter them out or provide fallbacks to defaults. No one likes undefined results sneaking into their arrays!

const safeProps = objArray .filter(obj => obj != null) // Discarding party poopers! .map(obj => obj.prop || 'Default'); // Fallback to 'Default' if prop is missing

If you are forcing JavaScript to time travel back to IE8, bear in mind that map() was non-existent then. Use polyfills, or better still, let’s keep up with time and opt for modern browsers:

// IE8 be like: "What the heck is a map?" 😅

Replacing lodash's _.pluck() with _.map() and _.property() keeps your library slim and fit:

// Using Lodash's deprecated pluck() const propArray = _.pluck(objArray, 'prop'); // After gym: Comparator with map() and property() const trimmedPropArray = _.map(objArray, _.property('prop')); // Brutal weight cut 😄