Search code examples
javascriptobjectdestructuring

Iterating over a multi-level object?


I have a multi-level object that has dynamic names and goes about 2 levels deep. I came up with a solution that works if there is only one dynamic-object, however I am having trouble writing the loop for multiples. Here are the basics.

My object looks like this:

{ 
  dynamic_name1: { 
    mods: [ 
      [Object], [Object] 
    ] 
  }, 

  dynamic_name2: { 
    mods: [ 
      [Object], [Object]
    ] 
   }, 

  dynamic_name3: { 
    mods: [ 
      [Object], [Object]
    ] 
  } 
}

Basically, I want to iterate over this object, and get the objects from within each of the respective mods arrays, then push them to a different array.

I am getting this object, with the variable container, then structure like so:

const [objectKeys] = Object.keys(container);
const modsList = container[objectKeys].mods;

This solution works really well because then I just add it to my new array like this:

const myMods = [...modsList]

However, this whole functionality seems to break when I try to loop it. here's what I have so far:

for (j = 0; j < container.length; j++){
  const [objectKeys] = Object.keys(container);
}

but when trying to log [objectKeys] I get undefined. Any idea how I could do this?


Solution

  • I would get all the mods reducing a map over your dynamic sub-objects, something like:

    const container = { 
      dynamic_name1: { 
        mods: [ 
          1, 2
        ] 
      }, 
    
      dynamic_name2: { 
        mods: [ 
          3, 4
        ] 
       }, 
    
      dynamic_name3: { 
        mods: [ 
          5, 6
        ] 
      } 
    }
    
    const mods = Object.values(container)
                       .map(sub => sub.mods)
                       .reduce(
                         (result, mods) => [...result, ...mods],
                         []
                       )
    
    console.log(mods)
    // [1, 2, 3, 4, 5, 6]
    

    This way you can loop at the end.