JavaScript display objects refer to elements in the DOM used for rendering webpage content, manipulated dynamically via JavaScript for interactive user experiences.
When displaying a JavaScript object, the output will show as [object Object].
Example
// Create an Object const person = { name: “John”, age: 30, city: “New York” }; document.getElementById(“demo”).innerHTML = person; |
Here are several methods to present JavaScript objects:
Object.values()
to list object valuesJSON.stringify()
to output the objectThe properties of an object can be displayed as a string.
Example
// Create an Object const person = { name: “John”, age: 30, city: “New York” }; // Display Properties document.getElementById(“demo”).innerHTML = person.name + “,” + person.age + “,” + person.city; |
The properties of an object can be gathered in a loop.
Example
// Create an Object const person = { name: “John”, age: 30, city: “New York” }; // Build a Text let text = “”; for (let x in person) { text += person[x] + ” “; }; // Display the Text document.getElementById(“demo”).innerHTML = text; |
Note: You must use
|
Object.values()
generates an array from the property values.
// Create an Object const person = { name: “John”, age: 30, city: “New York” }; // Create an Array const myArray = Object.values(person); // Display the Array document.getElementById(“demo”).innerHTML = myArray; |
Object.entries() simplifies using objects in loops.
Example
const fruits = {Bananas:300, Oranges:200, Apples:500}; let text = “”; for (let [fruit, value] of Object.entries(fruits)) { text += fruit + “: “ + value + “<br>”; } |
JavaScript objects can be converted to a string using the JSON.stringify()
method.
JSON.stringify()
is built into JavaScript and supported by all major browsers.
Note: The output will be a string in JSON notation:
|
Example
// Create an Object const person = { name: “John”, age: 30, city: “New York” }; // Stringify Object let myString = JSON.stringify(person); // Display String document.getElementById(“demo”).innerHTML = myString; |