JavaScript Display Objects


How to Display JavaScript Objects?

When you show a JavaScript object, it will appear as [object Object].

Here are some usual ways to show JavaScript objects:

  • Showing the characteristics of an object by its name.
  • Showing the Characteristics of an Object in a Loop
  • Showing the object using Object.values()
  • Showing the object using JSON.stringify()

Displaying Object Properties

An object's characteristics can be shown in the form of a string.


Displaying the Object in a Loop

You can gather the characteristics of an object using a loop.

You need to utilize person[x] within the loop.

person.x won't function correctly because x is a variable.


Using Object.values()

You can turn any JavaScript object into an array using the Object.values() method.

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

const myArray = Object.values(person);

myArray is a JavaScript array that is ready to be shown.


Using JSON.stringify()

You can turn any JavaScript object into a string using the function JSON.stringify().

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

let myString = JSON.stringify(person);

The JavaScript string, myString, is now prepared for display.

The outcome will be a series of characters formatted in JSON notation.

{"name":"John","age":50,"city":"New York"}

The JSON.stringify() function is a part of JavaScript and works in all the main web browsers.


Stringify Dates

The JSON.stringify function transforms dates into strings.


Stringify Functions

The function JSON.stringify cannot convert functions into strings.

To solve this issue, you can change the functions into strings before converting them into a string format.


Stringify Arrays

You can convert JavaScript arrays into strings.

The output will be a text formatted using JSON notation.

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