1

How would I loop through each of the value: properties in the object below? My attempt in the console.log below obviously does not work, but that is what I was trying to accomplish. console.log(key) would output "A1" "A2", but I can not figure out how to loop through and retrieve the names or values of deeper leveled properties.

var object = {
    A1: {
        B1: {
            C1: "A"
        },
        B2: {
            C1: "B"
        },
        B3: {
            C1: "C"
        },
    },
    A2: {
        B4: {
            C1: "D"
        },
        B5: {
            C1: "E"
        },
        B6: {
            C1: "F"
        }
    }
};

for (var key in object) {
    console.log(object[key][key].value);
}
Uncle Slug
  • 853
  • 1
  • 13
  • 26

3 Answers3

6
var object = {
    A1: {
        B1: {
            C1: "A"
        },
        B2: {
            C1: "B"
        },
        B3: {
            C1: "C"
        },
    },
    A2: {
        B4: {
            C1: "D"
        },
        B5: {
            C1: "E"
        },
        B6: {
            C1: "F"
        }
    }
};

function printObj(obj) {
  for (var key in obj) {
    var value = obj[key];
    if (typeof value === 'object') {
      printObj(value);
    } else {
      console.log(value);
    }
  }
}

printObj(object);

Just use Recursion

lyd600lty
  • 93
  • 4
3

You are probably looking for nested for loops. For iterating over this particular object (which we know has exactly three levels of nesting) you might try something like this:

for(var key1 in object) {
  for(var key2 in object[key1]) {
    for(var key3 in object[key1][key2]) {
      console.log(object[key1][key2][key3]);
    }
  }
}

Output:

"A"
"B"
"C"
"D"
"E"
"F"
Nigel Nelson
  • 110
  • 1
  • 9
1

Use nested loops:

var object = {
  A1: {
    B1: {
      C1: "A"
    },
    B2: {
      C1: "B"
    },
    B3: {
      C1: "C"
    },
  },
  A2: {
    B4: {
      C1: "D"
    },
    B5: {
      C1: "E"
    },
    B6: {
      C1: "F"
    }
  }
};
for (var key1 in object) {
  var e1 = object[key1];
  for (var key2 in e1) {
    var e2 = e1[key2];
    for (var key3 in e2) {
      console.log(e2[key3]);
    }
  }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612