JavaScript Display Objects
5 April 2025 | Category: JavaScript
When we talk about “displaying objects”, we mean:
- Showing an objectâs data in the console
- Showing it on a web page
- Converting it into string format
- Looping through properties to show values
đ ď¸ 1. Display in the Console
const person = {
name: "Rahul",
age: 22,
city: "Delhi"
};
console.log(person); // Shows whole object
console.log(person.name); // Rahul
console.log(person["age"]); // 22
You can also use console.table()
for a prettier output:
console.table(person);
đĽď¸ 2. Display on a Web Page (HTML)
You can use document.write()
or set content to an HTML element.
<p id="output"></p>
<script>
const person = {
name: "Aman",
age: 28
};
document.getElementById("output").innerHTML = person.name + " is " + person.age + " years old.";
</script>
đŞ 3. Convert Object to String â JSON.stringify()
Objects canât be shown directly as strings â you need to convert them using JSON.stringify()
.
const car = {
brand: "Honda",
model: "Civic"
};
document.getElementById("output").innerHTML = JSON.stringify(car);
// Output: {"brand":"Honda","model":"Civic"}
You can format it nicely like this:
JSON.stringify(car, null, 2); // Pretty format with indentation
đ 4. Loop Through Object and Display Properties
Using for...in
loop:
let text = "";
for (let key in car) {
text += key + ": " + car[key] + "<br>";
}
document.getElementById("output").innerHTML = text;
đ 5. Use Object.entries()
to Display Key-Value Pairs
const student = {
name: "Anjali",
marks: 95
};
const entries = Object.entries(student);
entries.forEach(([key, value]) => {
document.write(`${key}: ${value}<br>`);
});
đ Summary
Method | Use Case |
---|---|
console.log(object) | Show object in developer console |
document.write() | Write object properties in browser |
innerHTML | Insert object data into HTML |
JSON.stringify() | Convert object to readable string |
for...in loop | Loop and display all properties |
Object.entries() | Get key-value pairs for display |
â Example You Can Copy-Paste:
<!DOCTYPE html>
<html>
<body>
<h2>Display Object Example</h2>
<p id="demo"></p>
<script>
const user = {
username: "devin_wildz",
level: "Frontend Developer",
skills: ["HTML", "CSS", "JavaScript", "React"]
};
let output = "";
for (let key in user) {
output += `${key}: ${user[key]} <br>`;
}
document.getElementById("demo").innerHTML = output;
</script>
</body>
</html>