-2

now I'm using JSON Objects to compare information, and I don't know if there is a way to get the level of depth in a specific key.

For example, I have this JSON Object:

{
   hi : "everyone",
   hereIs : {
      an : "Object"
   }
}

And I need to know in a for ... in loop the level of depth of each key:

hi is in level 0
hereIs is in level 0
an is in level 1

What I have for the moment is this:

 // Loop through the first object
     for (key in obj1) {
          if (obj1.hasOwnProperty(key)) {
               compare(obj1[key], obj2[key], key);
          }
     }

The "compare" function if made to verify if the information in the objects are equal, and if not, it add the info in a third object, what I would like to know is how could I get the level of the key in obj1 and pass it to the "compare" function.

Thank you for your help.

2 Answers2

3

You can try this:

function showDepth(obj, lvl){
  if(!lvl) lvl = 0;
  Object.keys(obj).map(key => {
    console.log(key + ' is in level ' + lvl);
    if(typeof obj[key] === "object") {
      showDepth(obj[key], lvl+1);
    }
  });
}
showDepth({
   hi : "everyone",
   hereIs : {
      an : "Object"
   }
});
Prawin soni
  • 423
  • 2
  • 8
1

You could use JSON.stringify's replacer as follows:

const obj = {
  hi: "everyone",
  hereIs: {
    an: "Object",
    and: {
      another: "one"
    }
  }
}

let level = -1;

JSON.stringify(obj, function(k, v) {
  if (level >= 0)
    console.log(k, "is in level", level);
  if (typeof v == "object")
    level++;
  return v;
});
shrys
  • 5,860
  • 2
  • 21
  • 36