8

Hi there i have an nested object that looks like this

var dogTypes = {
GermanShepard {color: "black and white"},
Beagle       {color: "brown and white"},
cheuwahwah  {color: "green and white"},
poodle:    {color: "purple and white"},
 }

im trying to loop through all the properties in a nested object i know how to do that with a regular object but not a nested one so if someone could help me that would be great.

 for (var key in dogTypes) {
 console.log(key + " : " + dogTypes[key])
 }

heres my code which prints out

 GreatDane : [object Object]
   GermanSheppard : [object Object]
   Beagle : [object Object]
   BullDog : [object Object]

where would i incorporate the color property in the for in loop please help!! thanks

Sammy
  • 85
  • 1
  • 1
  • 4

2 Answers2

4

"im trying to loop through all the properties in a nested object"

A nested object is a regular object. You just need a nested loop if you want to reach all properties in the nested objects.

var dogTypes = {
  GermanShepard: {
    color: "black and white"
  },
  Beagle: {
    color: "brown and white"
  },
  cheuwahwah: {
    color: "green and white"
  },
  poodle: {
    color: "purple and white"
  },
};

for (var key in dogTypes) {
  for (var key2 in dogTypes[key]) {
    console.log(key, key2, dogTypes[key][key2]);
  }
}

If there's only one, known key in the nested object, then you don't need a loop, but then you also don't really need a nested object.

spanky
  • 2,768
  • 8
  • 9
0

Its simple as:

console.log(key + " : " + dogTypes[key].color)

to access the color property. If you add more levels have a look at: looping through an object (tree) recursively

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46