HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Object Display

Displaying a JavaScript object isn't as simple as displaying a string or a number. If you try to write an object directly to the page using innerHTML or alert(), you will often see [object Object]. In this lesson, we will learn how to properly display object data.


Methods for Displaying Objects

There are several common ways to display the content of an object:

1. Displaying Properties by Name

The simplest way is to manually access and display each property.

const person = { name: "Mim", age: 25, city: "Dhaka" };

document.getElementById("demo").innerHTML = person.name + ", " + person.age + ", " + person.city;

2. Using Object.values()

This method creates an array containing all the values of an object. You can then display that array easily.

const person = { name: "Mim", age: 25, city: "Dhaka" };
const myArray = Object.values(person);

console.log(myArray); // ["Mim", 25, "Dhaka"]

3. Using Object.entries()

Similar to Object.values(), but it returns an array of [key, value] pairs.


Using JSON.stringify()

This is the most popular way to convert a full JavaScript object into a string. It is widely used for debugging and sending data to web servers.

const person = { name: "Mim", age: 25, city: "Dhaka" };
let myString = JSON.stringify(person);

console.log(myString); // '{"name":"Mim","age":25,"city":"Dhaka"}'
Note: JSON.stringify() will automatically convert dates into strings, but it will remove functions from the object.

Displaying in a Loop

You can use a for...in loop to build a string dynamically from object properties:

const person = { name: "Mim", age: 25, city: "Dhaka" };

let text = "";
for (let x in person) {
  text += person[x] + " ";
}

Key Points to Remember

  • Directly printing an object results in [object Object]
  • Use JSON.stringify() for a quick text representation
  • Use Object.values() to turn the data into a usable array
  • JSON stringification is the standard for API communication
  • Functions are lost when using JSON stringify, so keep that in mind during debugging
  • For development, console.log(obj) is the best way to inspect nested objects