如何遍历存储在数组列表中的对象

伊阿利莫

任何人都可以提示我如何使用forEach方法迭代货币数组以获取对象的ID和名称。

  const currencies = [{
        id: 'USD', name: 'US Dollars'
      }, {
        id: 'UGX', name: 'Ugandan Shillings'
      }, {
        id: 'KES', name: 'Kenyan Shillings'
      }, {
        id: 'GHS', name: 'Ghanian Cedi'
      }, {
        id: 'ZAR', name: 'South African Rand'
      }];
var populateCurrencies = (currencies)=>{
    currencies.forEach(function(id,name){
     

    }
  }
  

尼克·帕森斯

也许您会感到困惑,因为forEach回调中的参数名称不能正确表示它们的实际含义。

.forEach回调函数的第一个参数是您当前对其进行迭代元素在您的情况下,它是您当前在currencies阵列中使用的对象它不是id您命名的样子。

.forEach回调中的第二个参数是索引,但是,您不需要它,因为您所需要的只是对象(这是第一个参数)

因此,如果第一个参数是对象,则可以在每次迭代中使用点符号访问其nameid属性

请参见下面的示例:

const currencies = [{id:"USD",name:"US Dollars"},{id:"UGX",name:"Ugandan Shillings"},{id:"KES",name:"Kenyan Shillings"},{id:"GHS",name:"Ghanian Cedi"},{id:"ZAR",name:"South African Rand"}];

const populateCurrencies = (currencies) => {
  currencies.forEach(function(obj) {
    console.log(obj.name, obj.id);
  });
}

populateCurrencies(currencies)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章