Plucking properties from an array of objects
JavaScriptAll snippets in this category →
Posted on One of the more common tasks when mapping over arrays in JavaScript is extracting properties from objects. Instead of using individual arrow functions, we can create a reusable helper function that does the plucking for us.
const countries = [
{ name: "France", capital: "Paris" },
{ name: "Spain", capital: "Madrid" },
{ name: "Italy", capital: "Rome" }
]
// we can extract the attributes with individual arrow functions
countries.map(country => country.name) // ⇒ ["France", "Spain", "Italy"]
countries.map(country => country.capital) // ⇒ ["Paris", "Madrid", "Rome"]
// this function allows us to write that arrow function shorter
const pluck = property => element => element[property]
countries.map(pluck("name")) // ⇒ ["France", "Spain", "Italy"]
countries.map(pluck("capital")) // ⇒ ["Paris", "Madrid", "Rome"]
const countries = [
{ name: "France", capital: "Paris" },
{ name: "Spain", capital: "Madrid" },
{ name: "Italy", capital: "Rome" }
]
// we can extract the attributes with individual arrow functions
countries.map(country => country.name) // ⇒ ["France", "Spain", "Italy"]
countries.map(country => country.capital) // ⇒ ["Paris", "Madrid", "Rome"]
// this function allows us to write that arrow function shorter
const pluck = property => element => element[property]
countries.map(pluck("name")) // ⇒ ["France", "Spain", "Italy"]
countries.map(pluck("capital")) // ⇒ ["Paris", "Madrid", "Rome"]
const countries = [
{ name: "France", capital: "Paris" },
{ name: "Spain", capital: "Madrid" },
{ name: "Italy", capital: "Rome" }
]
// we can extract the attributes with individual arrow functions
countries.map(country => country.name) // ⇒ ["France", "Spain", "Italy"]
countries.map(country => country.capital) // ⇒ ["Paris", "Madrid", "Rome"]
// this function allows us to write that arrow function shorter
const pluck = property => element => element[property]
countries.map(pluck("name")) // ⇒ ["France", "Spain", "Italy"]
countries.map(pluck("capital")) // ⇒ ["Paris", "Madrid", "Rome"]
const countries = [
{ name: "France", capital: "Paris" },
{ name: "Spain", capital: "Madrid" },
{ name: "Italy", capital: "Rome" }
]
// we can extract the attributes with individual arrow functions
countries.map(country => country.name) // ⇒ ["France", "Spain", "Italy"]
countries.map(country => country.capital) // ⇒ ["Paris", "Madrid", "Rome"]
// this function allows us to write that arrow function shorter
const pluck = property => element => element[property]
countries.map(pluck("name")) // ⇒ ["France", "Spain", "Italy"]
countries.map(pluck("capital")) // ⇒ ["Paris", "Madrid", "Rome"]