Skip to content Skip to sidebar Skip to footer

Dynamically Accessing Object Property In .map Array Function

i want to have reusable function that maps an array of objects based on property passed as parameter to function. Here's my code: let arr = [ { country: 'poland', populat

Solution 1:

You just need to use bracket notation, like this:

function filterMyArr (myArr, condition) {
  return myArr.map(element => element[condition])
}

Where you pass the condition as a string as a name of a property in your object.

Note:

But just be aware that calling the function without this condition argument, will throw an error, when you do:

console.log(filterMyArr(arr))

Solution 2:

You were very close. Try this

let arr = [
  {
    country: 'poland',
    population: 380000
  },
  {
    country: 'bangladesh',
    population: 3492423
  }
]

function filterMyArr (myArr, condition) {
  return myArr.map(element => element[condition])
}

console.log('Countries - ', filterMyArr(arr, 'country'))

console.log('Population - ', filterMyArr(arr, 'population'))

Solution 3:

You need to pass second argument (property) as a string and access it using bracket notation:

let arr = [
  {country: 'poland', population: 380000},
  {country: 'bangladesh', population: 3492423}
];

function filterMyArr (myArr, prop) {
  return myArr.map(obj => obj[prop]);
}

console.log(filterMyArr(arr, 'country'));
console.log(filterMyArr(arr, 'population'));

Post a Comment for "Dynamically Accessing Object Property In .map Array Function"