【问题标题】:Dynamically accessing object property in .map array function [duplicate]动态访问.map数组函数中的对象属性[重复]
【发布时间】:2019-04-15 04:37:10
【问题描述】:

我想要一个可重用的函数,它根据作为参数传递给函数的属性映射一组对象。

这是我的代码:

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) 并获得类似的结果。我希望它可以重复使用,这样我就可以将它用于人口或任何其他财产。谢谢。

【问题讨论】:

    标签: javascript arrays object properties


    【解决方案1】:

    您需要将第二个参数(属性)作为字符串传递并使用括号表示法访问它:

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

    【讨论】:

    • 谢谢。忘了尝试括号,我的错:/
    【解决方案2】:

    你们很亲密。试试这个

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

    【讨论】:

      【解决方案3】:

      你只需要使用bracket notation,像这样:

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

      您将condition 作为string 作为object 中的属性名称传递。

      注意:

      但请注意,在没有此 condition 参数的情况下调用函数会引发错误:

      console.log(filterMyArr(arr))
      

      【讨论】:

      • 您可以将condition的默认值设置为country
      • @Mohammad 是的,我们可以,这是一种做事方式。这取决于逻辑。
      猜你喜欢
      • 1970-01-01
      • 2018-10-18
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2011-08-10
      相关资源
      最近更新 更多