DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Discussion on: Plucking properties from object arrays in JavaScript

Collapse
 
heyrohit profile image
Rohit Gupta • Edited on

How about this,

const getKey = (array,key) => array.map(a => a[key]);

const countries = [
  { name: 'France', capital: 'Paris'  },
  { name: 'Spain',  capital: 'Madrid' },
  { name: 'Italy',  capital: 'Rome'   }
]

getKey(countries,'name') // even shorter
Enter fullscreen mode Exit fullscreen mode
Collapse
 
domhabersack profile image
Dom Habersack Author

Very nice. I usually use the other one because that way it’s easier to chain with other array methods: .filter() an array, .map() some values out of its elements, .sort() the result, maybe run a .reduce() over it, all in the same chain.

If that’s not the scenario, I like your solution better.