Skip to content

Instantly share code, notes, and snippets.

@nickfun
Last active December 16, 2015 11:29
Show Gist options
  • Save nickfun/5428231 to your computer and use it in GitHub Desktop.
Save nickfun/5428231 to your computer and use it in GitHub Desktop.
Recursive print for Javascript.
function print_r( data, key, level ) {
if( key !== 0 ) {
key = key || false;
}
level = level || 0;
if( _.isArray( data ) ) {
if( typeof key === 'boolean' ) {
print_r('[', false, level);
} else {
print_r(key + ': [', false, level);
}
_.each( data, function( value, index ) {
print_r( value, index, level+1);
});
print_r(']', false, level);
} else if ( _.isObject( data ) ) {
if( typeof key === 'boolean' ) {
print_r('{', false, level);
} else {
print_r(key + ': {', false, level);
}
_.each( data, function( value, key ) {
print_r( value, key, level+1 );
});
print_r('}', false, level);
} else {
var space = '';
while( level > 0 ) {
space += ' ';
level--;
}
if( typeof key === 'boolean' ) {
print( space + data + "\n" );
} else if( _.isString(data) ) {
print( space + key + ': "' + data + '"' + "\n" );
} else if( typeof data === 'boolean' ) {
print( space + key + ': [boolean] ' + data + "\n" );
} else {
print( space + key + ': ' + data + "\n");
}
}
}
@nickfun
Copy link
Author

nickfun commented Apr 21, 2013

Note that this depends on Underscore or LoDash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment