How to Display a JavaScript Object
In this snippet, you will find fast-solutions on how to display an object in JavaScript.
For example, when you need to print the object for some debugging purposes, you can use the following code:
Please, notice that you only need to log the object. The following code will not work in this case:
Also, take into consideration that a comma may be used in the log method. The initial line of the output will be the string, and only then the object can be rendered. Here is an example:
There is also an alternative method: it’s the native JSON.stringify() method. It operates with nested objects, and all the major browsers support it.
Here is an example of using the JSON.stringify() method:
You can apply the custom JSON.stringify replacer, in case the following JavaScript error occurs:
Describing the JSON.stringify() Method
The JSON.stringify() method is targeted at converting JavaScript objects into strings. The data should be a string at the time of sending it to a web server. It accepts the following parameters: value, replacer, space. The value is the one that needs to be converted into a JSON. The replacer is considered an optional parameter. It can be an altering function, either an array used as a selected filter for the stringify. In case the value is empty or null, all the properties of the object included in a string. Space is an optional parameter, as well. It is used for controlling spacing inside the final string created using the JSON.stringify() method. The return value returns a string for a particular value.
The Usage of JavaScript Objects
Objects are the most important data-type, forming the building block for modern JavaScript. They are different from primitive data types in the sense that when the primitives store a single value each, objects are more complicated and may contain any combination of primitives, as well as reference data types.
An object itself is related to reference data types.
Objects may be created using figure brackets {…} with an optional list of properties.