0

In debugging, I sometimes have an object comprised of a number of key:value pairs, and I need to look at the individual pairs. I have the following code to do that.

for(let [key, value] of Object.entries(params)) {
  console.log('(key, value) : (' + key + ', ' + value + ')');
}

But now, I've come across an instance where value is itself an object. All I get in the log for value is [object: Object] which tells me little.

In an attempt to drill down into value when it is an object, I tried:

for(let [key0, value0] of Object.entries(params)) {
  console.log('(key, value) : (' + key0 + ', ' + value0 + ')');
  while(typeof value0 === 'object') {
    for(let [key1, value1] of Object.entries(value0)) {
      console.log('typeof val == obj: (' + key1 + ', ' + value1 + ')');
    }  // end for-let
  }  // end while
}  // end for-let

But all I managed to do, apparently, was to put the computer in an endless loop.

Perhaps a recursive function is what I need. I know they exist because I've been reading Eloquent JavaScript (Haverbeke, Marijn, 2d ed.), but I'm not (yet?) well enough versed in JavaScript to figure out one on my own.

Can anyone help? I really need to look inside value when it's an object, whether or not by a recursive function.

Thanks so much for reading this far and for your time and effort.

Edit:

I think I see why the endless loop. I do nothing in the while statement group to change the type of value0, so the condition is always true. I never break the while condition. But I still need a solution.

alxfyv
  • 389
  • 1
  • 6
  • 18
  • `console.log()` works much better when you give it objects to log instead of strings... `console.log('(key, value):', key, value)` – Phil Jun 17 '19 at 04:57
  • If you need to look at the whole object there as a string, you can make it pretty and semi-readable with `JSON.stringify`, but that's pretty weird to do. I'd prefer to just log the object alone (don't concatenate it with anything) – CertainPerformance Jun 17 '19 at 04:58
  • can't you use console.dir ? – Gourishankar Jun 17 '19 at 04:59
  • _"In debugging..."_ use a debugger. Logging to the console is a poor substitute – Phil Jun 17 '19 at 04:59
  • 1
    The `while` loop that is wrapping your iteration of Value1 is what is giving your real headaches in your debugging. if Value0 is an Object you will continue to iterate over Value1 forever without any break logic. – rmrouse88 Jun 17 '19 at 05:05
  • 2
    Just do `console.log(params)` - the browser and node.js have already implemented the recursive code for you - you don't need to do it yourself. Do NOT do `console.log("some string" + params)`! If you need a string to identify you log do `console.log("some string", params)` – slebetman Jun 17 '19 at 06:34

0 Answers0