Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Pretty Print JavaScript Object & Array

5.00/5 (2 votes)
7 May 2016CPOL3 min read 25K   181  
Pretty print function for JavaScript Object & Array

Image 1

Introduction

This is a little script that I use to pretty print a JavaScript Object & Array. I find it very helpful during JavaScript debugging, but I'm sure there are more uses than that. This code doesn't reinvent the wheel, there are similar scripts that do the same task and I'm sure you can Google them all. This is simply my version of it.

There are two versions of this code, one with jQuery (not a jQuery plugin) and one of pure JavaScript. They do the same exact thing but they are intended for different client environments. So, depending on whether jQuery is present or not, you have a choice between these two versions.

It is worth noting that this code detects objects & arrays circular recursions, so it doesn't go off on an infinite loop. The function is called objectToString and if you wish to hook it up to object & array toString(), you can add this code at the end of the file:

JavaScript
Object.prototype.toString = function (options) {
    objectToString(this, options);
};

Array.prototype.toString = function (options) {
    objectToString(this, options);
};

objectToString Options

  • toHTML - If false, the function returns a string (good for alert()). If true, the returned string is formatted for HTML.
  • pre - If true, the HTML is wrapped with pre tag. Otherwise, the HTML is wrapped with span tag.
  • name - The name of the root object.
  • indentSize - The size of the space indentation. Default 4 spaces.
  • indent - An indentation string. indentSize is ignored if this is not null.
  • compact - Compact mode tries to keep objects and arrays in one line or less lines as possible.
  • short - The closing parenthesis does not take a new line.
  • flat - The result is flatten to a single line.
  • keyQuotations - Quotations surround the keys.
  • stringQuotations - Quotations surround a string value.
  • assignmentPrimitive - Assignment operator for primitive types. Default " = ".
  • assignmentObject - Assignment operator for Objects & arrays. Default ": ".
  • emptyStringOnEmpty - Empty string when the value is null or undefined.
  • comma - Comma between items.
  • align - Align object values on the same column. Works better with pre option (fixed-width font).
  • arrayIndices - Adds numeric indices for array items.
  • ignoreNull - Ignore items with null value.
  • ignoreUndefined - Ignore items with undefined value.
  • ignoreEmpty - Ignore items with null value or undefined value.
  • ignoreNaN - Ignore items with NaN value.
  • ignoreRegExp - Ignore items with regular expression RegExp value.
  • ignoreFunction - Ignore items with function value.
  • ignoreEmptyArray - Ignore items with empty array as value.
  • ignoreEmptyObject - Ignore items with empty object as value.
  • ignoreRecursion - Ignore items with circular recursions as value.
  • json - Prints values similar to JSON.stringify().
  • formatNumber - Format number with thousands group separator.
  • intFixed - Converts an int number into a string, keeping a specified number of decimals.
  • floatFixed - Converts a float number into a string, keeping a specified number of decimals.
  • ignoreDatePart - Print Date value without the date part.
  • ignoreTimePart - Print Date value without the time part.
  • milliseconds - Print time part of a Date value with milliseconds.
  • functionBody - Print the body of a function. If disabled, only the function declaration is shown.
  • sort - Sort the items by name. Case Sensitive.
  • sortInsensitive - Sort the items by name. Case Insensitive.
  • onValue - A callback that lets the user determines how the value will be printed.
    JavaScript
    objectToString(obj, {
        onValue: function (props) {
            props.key;         // the key
            props.value;       // the original value
            props.formatValue; // the formatted value by objectToString
            props.type;        // the type of the value
            props.depth;       // how deep in the hierarchy the item is located
    
            return props.formatValue;
        }
    });
  • styles - Set the style for various elements in the HTML.
    JavaScript
    objectToString(obj, {
        styles: {
            root:       { style: "font-style: italic;" },
            key:        { color: "blue", bold: true },
            assignment: { color: "#AD6A00" },
            value:      { class: "valueStyle" },
            string:     { color: "green" }
        }
    });

The elements that the style is applicable for are:

  • root - The style of the wrapper (span/pre) of the HTML.
  • key - The style of the keys.
  • assignment - The style of the assignment operators.
  • value - The style of the values.
  • string - The style of string values. When set, it is combined with the "value" style.

A style is defined by:

  • color - CSS color, such as a named color or a color hex.
  • bold - If true, set the font to bold.
  • style - CSS style string, items separated by semicolon.
  • class - Set the HTML class attribute.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)