如何遍历嵌套对象

Sam*_*mmy 6 javascript loops nested properties object

嗨,我有一个看起来像这样的嵌套对象

var dogTypes = {
GermanShepard {color: "black and white"},
Beagle       {color: "brown and white"},
cheuwahwah  {color: "green and white"},
poodle:    {color: "purple and white"},
 }
Run Code Online (Sandbox Code Playgroud)

我试图遍历嵌套对象中的所有属性,我知道如何使用常规对象而不是嵌套对象来执行此操作,因此如果有人可以帮助我,那就太好了。

 for (var key in dogTypes) {
 console.log(key + " : " + dogTypes[key])
 }
Run Code Online (Sandbox Code Playgroud)

这是我打印出来的代码

 GreatDane : [object Object]
   GermanSheppard : [object Object]
   Beagle : [object Object]
   BullDog : [object Object]
Run Code Online (Sandbox Code Playgroud)

我将在哪里将颜色属性合并到 for in 循环中,请帮忙!谢谢

spa*_*nky 4

“我试图循环遍历嵌套对象中的所有属性”

嵌套对象是常规对象。如果您想访问嵌套对象中的所有属性,则只需要一个嵌套循环。

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]);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果嵌套对象中只有一个已知键,那么您不需要循环,但您也不需要真正需要嵌套对象。