【问题标题】:Javascript - iterating thru object arrayJavascript - 遍历对象数组
【发布时间】:2023-01-18 04:30:17
【问题描述】:
   const module = {
      video: [
         { id: 1, title: 'video', component: <Video />},
      ],
      condensed: [
         { id: 2, title: 'condensed', component: <Condensed /> },
      ],
      full: [
         { id: 3, title: 'full', component: <Full /> },
      ],
   };

有没有办法循环遍历其中数组被命名的对象数组?希望我使用正确的语言来描述这一点。 我正在为每个数组打印出 id 和 title。

如果数据看起来像这样,我相信我可以使用 for 循环(但我意识到我可以使用 forEach 或 map):

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

for (var key in module.video) {
    var obj = module.video[key];
    // ...
}

【问题讨论】:

  • 数组在对象中并没有什么特别之处。只需像使用任何其他包含数组的变量一样使用module.video
  • component 键中的那些字符串?
  • 在这种情况下,键不代表视频中的每个对象吗? obj.idobj.title 行不通吗?

标签: javascript arrays object


【解决方案1】:

forEach 对您的用例来说是最简单的

const module = {
  video: [
    { id: 1, title: "video" },
    { id: 2, title: "condensed" },
  ],
};

// option 1
module.video.forEach(({ id, title }) => {
  console.log(id, title);
});


// option 2
for (var key in module.video) {
  const { id, title } = module.video[key];
  console.log(id, title);
}

// option 3
for (const item of module.video) {
  const { id, title } = item;
  console.log(id, title);
}

【讨论】:

  • 我认为 OP 想要的是遍历标题中的每个数组,第一个video,第二个condensed,然后是Full
【解决方案2】:

如果你想遍历模块对象,你可以简单地使用 for...in

for (var el in module) {
        // Whatever you want to do
    }

您需要在哪里使用 module[el] 来获取整个对象。 如果你想要一种遍历所有孩子的孩子的方法,你可以简单地使用 for...in with a foreach inside

for (var el in module) {
        module[el].forEach((element) => {
            // Whatever you want to do
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多