【问题标题】:Loop through object's keys, then loop through values (because they are arrays)遍历对象的键,然后遍历值(因为它们是数组)
【发布时间】:2018-05-24 19:27:31
【问题描述】:

我有这个对象:

const example = {
  first: [*arrays objects*],
  second: [*arrays objects*],
  third: [*arrays objects*]
}

所以,情况是这样的:示例有 3 个键。每个键都有一个对象数组。首先,我想遍历对象键(第一、第二、第三),然后是它们的数组(使用 forEach)。我该怎么做?

【问题讨论】:

标签: javascript


【解决方案1】:

要循环一个对象,您需要指定要循环的对象,在这种情况下,我使用键

 Object.keys(example).forEach()

希望这会有所帮助:>

const example = {
  first: [{object: '1'},{object: '2'}],
  second: [{object: '3'},{object: '4'}]
}


Object.keys(example).forEach( entrie => {
  console.log(entrie)
  example[entrie].forEach(object => {
    console.log(object)
  })
})

【讨论】:

    【解决方案2】:

    Object.keys(object) 会将对象的键作为数组提供给您。

    const example = ...
    Object.keys( example ).forEach( ( key, index ) => {
        example[key]; // This is your array you wish to loop through.
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 2021-08-15
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多