Search code examples
javascriptdebuggingenumerablefor-in-loop

Is there a real alternative to "for ... in Object" in Javascript? (For debugging purposes)


As the MDN website says "for...in is most practically used for debugging purposes", which I also am doing. Is there any other way to get the same results instead of using for ... in to get an array of the keys?

Every other thread on stackoverflow I read about it gave alternatives like in the code below, that are not a solution for getting the same functionality.

var myp= document.createElement('p');
var a = new Array();
for (var each in myp) {  a.push(each);}
var b = Object.keys(myp);
var c = Object.getOwnPropertyNames(myp);

console.log(a,b,c);

Edit: The "duplicate" given as closing reason has a totally other question's purpose, and unsurprisingly their isn't an answer to my question on that duplicate thread either. :/


Solution

  • To emulate for..in, you would have to loop through the object's internal prototypes until you reached the top of the prototype chain.

    const emulateForIn = (obj) => {
      const properties = new Set();
      while (obj) {
        for (const key of Object.keys(obj)) {
          properties.add(key);
        }
        obj = Object.getPrototypeOf(obj);
      }
      return [...properties];
    }
    
    console.log(emulateForIn(document.createElement('p')));

    This probably isn't 100% spec-compliant, but it'll be close enough the vast majority of the time.

    That said, both this and your original code is quite odd, as is the recommendation you're quoting in your link - if you're debugging, usually just doing console.log(obj) or console.dir(obj) would be easier so as not to pollute the console with lots and lots of properties (you can expand the object on demand by clicking on it in any modern browser's devtools).