【问题标题】:How to iterate through an object stored in an array list [duplicate]如何遍历存储在数组列表中的对象[重复]
【发布时间】:2023-03-22 14:27:01
【问题描述】:

谁能提示我如何使用 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){
     

    }
  }
  

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

也许您会感到困惑,因为您在 forEach 回调中的参数名称错误地表示了它们的实际含义。

.forEach 回调函数的第一个参数是当前迭代的 元素。在您的情况下,它是您当前位于 currencies 数组中的对象。它不是你命名的id

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

因此,如果第一个参数是对象,您可以在每次迭代时使用dot notation 访问其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)

【讨论】:

    【解决方案2】:

    花括号添加到传递给 foreach 迭代器的项目的 extract properties

    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'
          }];
    
        currencies.forEach(function({id,name}){
         console.log(id,name);
    
        })

    【讨论】:

    • OP 看起来像个初学者。你应该避免破坏
    • OP 以错误的方式使用解构参数,因此获得知识的更好方法是花括号恕我直言。混合 const 和 var 也是一种不好的做法, map 比 forEach 更可取,并且提取与原始数组具有相同形式的数组可能是无用的。我只是试图用一个有效的代码来称呼他。
    【解决方案3】:

    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'
          }];
          
    currencies.forEach(currency =>    
         console.log(currency.id + " : " + currency.name)
    )

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 2021-07-30
      相关资源
      最近更新 更多