Friday 24 August 2018

Print the content of a JavaScript object

I was working on an Eclipse plugin based on a 3rd party API. One feature of their API I used allowed me to display a HTML page in a window. Sadly, within the applications frame, the page is impossible to debug with modern browser tools (e.g. FireBug in FireFox or DevTools in Chrome). I needed a different way to debug the JavaScript Objects I had on the page. Here is the useful solution which ending up helping me:

function printObject(o) {
  var out = '';
  for (var p in o) {
    out += p + ': ' + o[p] + '\n';
  }
  alert(out);
}

// test:
var myObject = {'something': 1, 'other thing': 2};
printObject(myObject);

Here we can access all the elements of an object using a foreach loop. The printObject function alert()s the object showing all properties and respective values.