Hello!

Tell me, please, how on pure Javascript is it better to iterate an object that has a certain level of nesting? For example:

o = {"test1": {"val": {"year":"1994"} }, "test2": {"val": {"body":"body1"} } } 

I try this:

 for (var key in o) { for (var k in o[key]) { for (var k1 in o[key][k]) { console.log(k1) console.log(o[key][k][k1]) } } } 

Am i doing right? Or can it be somehow simpler?

  • Nope, use recursion. Suddenly there will be an object nested at 7? And why do you need such a bust? - user207618
  • @Other, Ok, And if a fixed object, as in my example? - Pavel
  • @Pavel, what is the purpose of busting? - br3t
  • @Other, br3t I need, receiving a JSON string from the server, and converting it into an object select some data, then write this data into another object - Pavel
  • For this nesting it is possible and so (not forgetting hasOwnProperty , of course). Although it looks weird. - user207618

1 answer 1

 function t(obj){ if(/*объект*/){ // Перебираем for(var op in obj){ t(op); } } else { // Делаем чтото из свойством обекта // Например console.log(obj); } } 

Here it is. Something like this if I'm not mistaken