You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历含命名数组的JavaScript对象并输出id与title?

当然可以遍历这类对象啦!你只需要先遍历对象里的每个命名数组属性,再逐个处理数组内的元素就行,给你几种实用的实现方式:

方法1:for...in嵌套遍历(和你现有代码风格适配)

这种方式和你已经会的单个数组遍历逻辑衔接很顺畅,先遍历对象的所有键,再遍历对应数组的元素:

const module = {
  video: [
    { id: 1, title: 'video', component: <Video />},
  ],
  condensed: [
    { id: 2, title: 'condensed', component: <Condensed /> },
  ],
  full: [
    { id: 3, title: 'full', component: <Full /> },
  ],
};

// 遍历对象的每个属性(即各个命名数组)
for (const key in module) {
  // 确保只处理对象自身的属性(避免遍历到原型链上的冗余属性)
  if (module.hasOwnProperty(key)) {
    const currentArray = module[key];
    // 遍历当前数组内的每个元素
    currentArray.forEach(item => {
      console.log(`id: ${item.id}, title: ${item.title}`);
    });
  }
}

方法2:Object.values() + 双层forEach(更简洁)

ES6新增的Object.values()可以直接获取对象的所有值(也就是这里的各个数组),写法更清爽:

// 先拿到所有数组,再逐个遍历元素
Object.values(module).forEach(array => {
  array.forEach(item => {
    console.log(`id: ${item.id}, title: ${item.title}`);
  });
});

方法3:Object.entries()(需要用到数组键名时用)

如果你还需要用到video、condensed这些数组的名称,Object.entries()可以同时获取键名和对应数组:

// 同时拿到数组的键名和数组本身
Object.entries(module).forEach(([arrayName, array]) => {
  console.log(`正在遍历数组:${arrayName}`);
  array.forEach(item => {
    console.log(`  id: ${item.id}, title: ${item.title}`);
  });
});

这些方法都能帮你轻松遍历所有命名数组,输出每个元素的id和title。其中Object.values()和Object.entries()是ES6+的方法,现在主流浏览器和Node.js版本都支持,放心用就好~

内容的提问来源于stack exchange,提问作者Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:10:32