我想要一个可重用的函数,它根据作为参数传递给函数的属性来映射对象数组。
这是我的代码:
let arr = [
{
country: 'poland',
population: 380000
},
{
country: 'bangladesh',
population: 3492423
}
]
function filterMyArr (myArr, condition) {
return myArr.map(element => element.country)
}
console.log(filterMyArr(arr))
当我更改代码并尝试传递条件时,在执行时它不起作用。我想调用带有第二个参数的函数,例如 filterMyArr(arr,country) 并获得类似的结果。我希望它可以重复使用,这样我就可以将它用于人口或任何其他属性(property)。谢谢。
最佳答案
您只需使用 bracket notation ,像这样:
function filterMyArr (myArr, condition) {
return myArr.map(element => element[condition])
}
将条件
作为字符串
作为对象
中的属性名称传递。
注意:
但请注意,在不使用此 condition
参数的情况下调用函数会引发错误,当您执行以下操作时:
console.log(filterMyArr(arr))
关于javascript - 动态访问.map数组函数中的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262475/