How To Loop Through A Nested Object

This question already has an answer here:

  • How to loop through a plain JavaScript object with the objects as members? 17 answers

  • "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]);
      }
    }

    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

    链接地址: http://www.djcxy.com/p/52008.html

    上一篇: 在HTML中插入对象数据

    下一篇: 如何通过嵌套对象循环