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.
There are several common ways to display the content of an object:
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;
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"]
Similar to Object.values(), but it returns an array of
[key, value] pairs.
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"}'
JSON.stringify() will automatically convert dates
into strings, but it will remove functions from the object.
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] + " ";
}
[object Object]JSON.stringify() for a quick text representation
Object.values() to turn the data into a usable array
console.log(obj) is the best way to inspect nested objects