Yes, Icepickle is right. Recursion is the best way to handle this. Here is a solution:
var testObj = {
"one": {
"1": {"msg": "msg1"},
"2": {"msg": "msg2"},
"3": {"msg": "msg3"}
},
"two": {
"1": {"msg": "msg4"},
"2": {"msg": "msg5"},
"3": {"msg": "msg6"}
}
};
function follow(obj, n){
if (n == 1) {
return Object.keys(obj).map(function(k){
return obj[k];
});
}
else return Object.keys(obj).map(function(k){
return follow(obj[k], n-1);
});
}
console.log(follow(testObj, 2));
http://jsbin.com/boqekunaba/edit?js,console,output
As written, this will return the second level of the example JSON tree. You can change n to 3 to see what happens. The results are arrays to keep this concise. This is the result of using the map method, which is a shortcut for writing a for loop. If we simply want objects, we'll have to tweak this code a little more.