JS Display Objects
How to Display JavaScript Objects?
When you display a JavaScript object, you’ll get [object Object].
Example
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML = person;
Some options for displaying JavaScript objects are:
- Displaying the Object Properties by name
- Displaying the Object Properties in a Loop
- Displaying the object with Object.values()
- Displaying the object with JSON.stringify()
Displaying Object Properties
An object’s properties can be represented using 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;
Displaying Properties in a Loop
An object’s properties can be acquired 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 include person[x] in the loop.
Person.x will not work because x is a loop variable.
Using Object.values()
Object.values() generates an array of 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;
Using Object.entries()
Object.entries() makes it easy to utilize 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 + "
";
}
Using JSON.stringify()
JavaScript objects may be transformed to strings using the JSON function JSON.stringify().
JSON.stringify() is built into JavaScript and supported by all major browsers.
Note:
The output will be a string written in JSON format:
{“name”:”John”,”age”:50,”city”:”New York”}
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;