How to Display JavaScript Objects?

Displaying a JavaScript object will output [object Object].

Some common solutions to display JavaScript objects are:

• Displaying the Object Properties by name

• Displaying the Object Properties in a Loop

• Displaying the Object using Object.values()

• Displaying the Object using JSON.stringify()

EXAMPLE ❯


Displaying Object Properties

The properties of an object can be displayed as a string:

EXAMPLE ❯


Displaying the Object in a Loop

The properties of an object can be collected in a loop:

You must use person[x] in the loop.

person.x will not work (Because x is a variable).

EXAMPLE ❯


Using Object.values()

Any JavaScript object can be converted to an array using Object.values():

const person = {

  name: "John",

  age: 30,

  city: "New York"

};

const myArray = Object.values(person);

myArray is now a JavaScript array, ready to be displayed:

EXAMPLE ❯


Using JSON.stringify()

Any JavaScript object can be stringified (converted to a string) with the JavaScript function JSON.stringify()

JSON.stringify() is included in JavaScript and supported in all major browsers.

EXAMPLE ❯


Stringify Dates

JSON.stringify converts dates into strings:

EXAMPLE ❯


Stringify Functions

JSON.stringify will not stringify functions:

Example:

<script>

const person = {

  name: "John",

  age: function () {return 30;}

};

document.getElementById("demo").innerHTML = JSON.stringify(person);

</script>

In above example, It does not returns age,

Output:

{"name":"John"}

This can be "fixed" if you convert the functions into strings before stringifying.

EXAMPLE ❯


Stringify Arrays

It is also possible to stringify JavaScript arrays:

Following code's result will be a string following the JSON notation:

["John","Peter","Sally","Jane"]

EXAMPLE ❯