Advertisement
Advertisement


How can I display a JavaScript object?


Question

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.

2020/05/10
1
1664
5/10/2020 11:21:04 AM

Accepted Answer

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);
2020/02/27
1110
2/27/2020 3:05:03 PM


var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);
2014/02/19

console.dir(object):

Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

Note that the console.dir() feature is non-standard. See MDN Web Docs


try this :

console.log(JSON.stringify(obj))

This will print the stringify version of object. So instead of [object] as an output you will get the content of object.

2015/08/12

Well, Firefox (thanks to @Bojangles for detailed information) has Object.toSource() method which prints objects as JSON and function(){}.

That's enough for most debugging purposes, I guess.

2014/07/10

If you want to use alert, to print your object, you can do this:

alert("myObject is " + myObject.toSource());

It should print each property and its corresponding value in string format.

2010/09/09

Source: https://stackoverflow.com/questions/957537
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]