Dynamically accessing object property in .map array function [duplicate]

孤人 提交于 2020-03-05 03:21:33

问题


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',
    population: 380000
  },
  {
    country: 'bangladesh',
    population: 3492423
  }
]

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

console.log(filterMyArr(arr))

When i change code and try to pass condition, while executing it doesn't work. I want to call a function with second parameter for example filterMyArr(arr, country) and to have similar outcome. I want it to be reusable so i can use it for population or any other property. Thank you.


回答1:


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'))



回答2:


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))



回答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'));


来源:https://stackoverflow.com/questions/53262475/dynamically-accessing-object-property-in-map-array-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!