javascript – Iterate multi-level object

Question:

I have a 3-level object with a code that iterates through each level, if in case the levels increase I would like to improve it to make it more dynamic, you can use recursion, or even not recursion, but how could it be optimized?

var obj = [{
  "seccion1": {
    "level1": {
      first: "John",
      last: "Doe"
    },
    "level2": {
      first: "juan",
      last: "perez"
    }
  }
}]


obj.forEach(function(item) {

  Object.keys(item).forEach(function(key) {
    let value = item[key];
    
    Object.keys(value).forEach(function(key2) {
       console.log(value[key2].first, value[key2].last);
     
    });
  });
});

The result should be: seccion1 level1 john doe level2 juan perez

Answer:

You must do a recursive function, you avoid repeating code:

var obj = [{
  "seccion1": {
    "level1": {
      first: "John",
      last: "Doe"
    },
    "level2": {
      first: "juan",
      last: "perez"
    }
  }
}]

function iterarObjeto(objeto){
  Object.keys(objeto).forEach(function(key) {
  
    if(typeof(objeto[key]) === "object"){
     console.info(`objeto ${key} vamos a iterar!`);
     iterarObjeto(objeto[key])
    }else{
      console.log(objeto[key])
    }

  });
}
obj.forEach(function(item) {
  iterarObjeto(item)

});

We can avoid the last iteration, but you need to know the last iteration, you avoid going through the object again, the example below:

 const obj = [{ "seccion1": { "level1": { first: "John", last: "Doe" } , "level2": { first: "juan", last: "perez"} } }] const ultimaIteracion = 2 function iterarObjeto(objeto, numeroIteracion){ if (numeroIteracion == ultimaIteracion){ console.log(objeto); return; } Object.keys(objeto).forEach(function(key) { if(typeof(objeto[key]) === "object"){ console.info(`objeto ${key} vamos a iterar!`); iterarObjeto(objeto[key], numeroIteracion + 1) } }); } obj.forEach(function(item) { iterarObjeto(item, 0) });
Scroll to Top