Skip to content

Instantly share code, notes, and snippets.

@bwinant
Created May 6, 2018 12:57
Show Gist options
  • Save bwinant/03cf38f081c469e07a77da1e7f17d174 to your computer and use it in GitHub Desktop.
Save bwinant/03cf38f081c469e07a77da1e7f17d174 to your computer and use it in GitHub Desktop.
Recursively Print Javascript Object
'use strict';
const printObject = (obj, seen = [], level = 0) => {
if (seen.length === 0) {
seen.push(obj);
}
const indent = " ".repeat(level);
for (let k in obj) {
// It is possible object is not derived from Object.prototype
if(Object.prototype.hasOwnProperty.call(obj, k)) {
const v = obj[k];
if (v == null) {
console.log(indent + k + ': null');
}
else if (Array.isArray(v)) {
//console.log(indent + k + ': [' + v + ']');
console.log(indent + k + ': [');
printObject(v, seen, level + 1);
console.log(indent + ']')
}
else if (typeof v === 'function') {
console.log(indent + k + ': [Function]');
}
else if (typeof v === 'object') {
if (seen.indexOf(v) >= 0) {
console.log(indent + k + ': [CIRCULAR]');
}
else {
seen.push(v);
console.log(indent + k + ': {');
printObject(v, seen, level + 1);
console.log(indent + '}')
}
}
else {
console.log(indent + k + ': ' + v);
}
}
}
};
module.exports.printObject = printObject;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment