1

I would like to know how to loop through a nested object without specifying keys. I mean just to take the name of the object to do the loop. Is there any method to achieve it? You can see at the bottom what I tried. It actually works, but I want to know if there is a way to do this without mentioning the keys(hero, monster)

Object to loop through:

const characterData = {
  hero: {
    name: "Wizard",
    avatar: "images/wizard.png",
    health: 60,
    diceCount: 3,
    currentDiceScore: []
  },
  monster: {
    name: "Orc",
    avatar: "images/orc.png",
    health: 10,
    diceCount: 1,
    currentDiceScore: []
  },
};

Object.entries(characterData.hero).forEach(([key, value]) => {
  console.log(`${key}: ${value}`)
});
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65

1 Answers1

1

You can first iterate over Object.values() which, in this case, are the nested objects hero, monster and so on.. using Array.prototype.forEach(), and then your code that iterates over Object.entries() again using Array.prototype.forEach()

const characterData = {hero: {name: "Wizard",avatar: "images/wizard.png",health: 60,diceCount: 3,currentDiceScore: []},monster: {name: "Orc",avatar: "images/orc.png",health: 10,diceCount: 1,currentDiceScore: []},}

Object.values(characterData)
  .forEach(o => 
    Object.entries(o)
      .forEach(([k, v]) => 
        console.log(`${k}: ${v}`)))
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    Thanks Yosvel. I understand what you did. However, I could not do a good grasp of the square brackets in the second forEach. I know it might has something to do with arrays but I cant put the idea of what is actually doing down. – ArgentumCoder May 30 '22 at 16:09
  • 1
    @ArgentumCoder Object.entries callback sends two parameters as an array tuple `[key, value]`, eg.. `[[key,value], [key,value],...]` so -> `([k, v]) => ` destructors these into k & v. – Keith May 31 '22 at 10:18