Skip to content

Instantly share code, notes, and snippets.

@barmatz
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save barmatz/8792553 to your computer and use it in GitHub Desktop.

Select an option

Save barmatz/8792553 to your computer and use it in GitHub Desktop.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
function dumpObject(object/*[, depth, name, objectHistory]*/) {
var type = typeof object,
isArray = object instanceof Array,
isObject = type === 'object',
isString = type === 'string',
isFunction = type === 'function',
isUndefined = type === 'undefined',
isNull = object === null,
prefix = ((isUndefined || isNull) ? '' : isString ? '"' : isArray ? '[' : isObject ? '{' : ''),
posfix = ((isUndefined || isNull) ? '' : isString ? '"' : isArray ? ']' : isObject ? '}' : ''),
value = '',
tabs = '',
depth = arguments[1] || 0,
name = arguments[2] || '',
objectHistory;
if (!isUndefined && !isNull && (isArray || isObject)) {
objectHistory = arguments[3] || [];
if (objectHistory.indexOf(object) === -1) {
objectHistory.push(object);
for (var key in object) {
value += dumpObject(object[key], depth + 1, key, objectHistory) + ',\n';
}
value = value.replace(/,\n$/, '');
} else {
value = '"' + object.toString() + '"';
}
} else {
value = isUndefined ? 'undefined' : isNull ? 'null' : object.toString();
if (isFunction) {
value = value.replace(/\s+(?=([^'"]*['"][^'"]*['"])*[^'"]*$)/g, '');
}
}
for (; tabs.length < depth; tabs += '\t'); // jshint ignore:line
prefix = prefix + ((isArray || (isObject && !isNull)) ? '\n\r' : '');
posfix = ((isArray || (isObject && !isNull)) ? '\n\r' + tabs : '') + posfix;
return tabs + (name ? '"' + name + '": ' : ' ') + prefix + value + posfix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment