Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print content of JavaScript object? [duplicate]

Typically if we just use alert(object); it will show as [object Object]. How to print all the content parameters of an object in JavaScript?

like image 454
cometta Avatar asked Oct 26 '09 14:10

cometta


People also ask

Which method is used to print the JavaScript Object?

The JSON.stringify () method is used to print the JavaScript object. JSON.stringify () Method: The JSON.stringify () method is used to allow to take a JavaScript object or Array and create a JSON string out of it.

How do I print JSON objects in MDN?

MDN recommends using console.log(JSON.parse(JSON.stringify(obj)))over console.log(obj)for printing objects. This is done to avoid constant updates to the console whenever the value of the object changes. This method won’t work if you try to concat a string with the object, as shown below:

How do I make a copy of an object in JavaScript?

To make a “real copy” (a clone) we can use Object.assign for the so-called “shallow copy” (nested objects are copied by reference) or a “deep cloning” function, such as _.cloneDeep (obj). Advance your skils with video courses on JavaScript and Frameworks.

How does the JavaScript engine work with objects?

When we perform actions with the object, e.g. take a property user.name, the JavaScript engine looks at what’s at that address and performs the operation on the actual object. Now here’s why it’s important. When an object variable is copied, the reference is copied, but the object itself is not duplicated.


2 Answers

This will give you very nice output with an indented JSON object using JSON.stringify:

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4)); 

The second argument (replacer) alters the contents of the string before returning it.

The third argument (space) specifies how many spaces to use as white space for readability.

JSON.stringify documentation here.

like image 193
Igor Jerosimić Avatar answered Oct 23 '22 13:10

Igor Jerosimić


If you are using Firefox, alert(object.toSource()) should suffice for simple debugging purposes.

like image 27
Lukman Avatar answered Oct 23 '22 12:10

Lukman