How can I display a JavaScript object?

03/26/2020 01:00:01

How do I display the content of a JavaScript object in a string format like when we alert a variable?

The same formatted way I want to display an object.

Verified Answer (1035 Votes)

06/06/2009 01:15:48

If you want to print the object for debugging purposes, use the code:

var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)

will display:

screenshot console chrome

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that the object will be rendered:

console.log('My object: ', obj);
1035

Answer #2 (1975 Votes)

11/27/2010 22:52:28

Use native JSON.stringify method. Works with nested objects and all major browsers support this method.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()

Link to Mozilla API Reference and other examples.

obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

Use a custom JSON.stringify replacer if you encounter this Javascript error

"Uncaught TypeError: Converting circular structure to JSON"
1975

Answer #3 (390 Votes)

06/06/2009 01:18:30
var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
390
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.