问题
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