From an array of objects, extract value of a property as array
Here's how to extract an array of property values using map()
.
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!
ES6 offers an even better soultion with the for..of
loop. It brings the best of both worlds - performance and readability:
And if you're coding in style or handling more complex situations, libraries like Lodash or Ramda have got your back:
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!
ES6 permits destructuring within the map()
callback. It’s like picking the chocolate chips out of a cookie:
Dealing with nested properties? Don’t sweat it, map()
has you covered:
When you need to extract multiple properties, just use map()
again!
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!
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:
Replacing lodash's _.pluck() with _.map()
and _.property()
keeps your library slim and fit:
Was this article helpful?