Search code examples
javascriptarraysobject

Javascript - iterating thru object array


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

Is there a way to loop through an object array in which the arrays are named? Hopefully I'm using the correct language to describe this. I'm looking to print out id and title for each array.

If the data looks like this, I believe I can use a for loop (but I realize that I can use forEach or 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];
    // ...
}

Solution

  • forEach will be simplest for your use case

    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);
    }

    If need to traverse the main object and inside arrays

    const module = {
      video: [{ id: 1, title: "video", component: "" }],
      condensed: [{ id: 2, title: "condensed", component: "<Condensed />" }],
      full: [{ id: 3, title: "full", component: "<Full />" }],
    };
    
    Object.entries(module).forEach(([key, items]) => {
      console.log("-->", key);
      items.forEach(({ id, title }) => {
        console.log(id, title);
      });
    });