JavaScript Object Display

Learn different ways to display and output object data

🖥️ Displaying Object Data

There are several ways to display object properties and values. Each method serves different purposes for debugging and presentation.


let person = {
    name: "Alice",
    age: 28,
    city: "London"
};

console.log(person); // Display entire object
                                    

Ways to Display Objects

📋

Individual Properties

Display specific properties

console.log(person.name);
console.log(person.age);
🔄

Loop Through Properties

Display all properties using loops

for (let key in person) {
    console.log(key + ": " + person[key]);
}
📄

JSON.stringify()

Convert object to JSON string

console.log(JSON.stringify(person));
🌐

HTML Display

Show objects in web pages

document.getElementById("demo").innerHTML = person.name;

🔹 Displaying Individual Properties

The simplest way to display object data is to access individual properties:

let student = {
    name: "Emma Watson",
    age: 22,
    major: "Computer Science",
    gpa: 3.8
};

// Display individual properties
console.log("Name: " + student.name);
console.log("Age: " + student.age);
console.log("Major: " + student.major);
console.log("GPA: " + student.gpa);

// Using template literals (ES6)
console.log(`Student: ${student.name}, Age: ${student.age}`);

Console Output:

Name: Emma Watson

Age: 22

Major: Computer Science

GPA: 3.8

Student: Emma Watson, Age: 22

🔹 Using for...in Loop

Display all properties using a loop:

let car = {
    brand: "Tesla",
    model: "Model 3",
    year: 2023,
    color: "red",
    electric: true
};

// Loop through all properties
console.log("Car Details:");
for (let property in car) {
    console.log(property + ": " + car[property]);
}

// Alternative with better formatting
console.log("\nFormatted Car Details:");
for (let key in car) {
    console.log(`${key.charAt(0).toUpperCase() + key.slice(1)}: ${car[key]}`);
}

Console Output:

Car Details:

brand: Tesla

model: Model 3

year: 2023

color: red

electric: true


Formatted Car Details:

Brand: Tesla

Model: Model 3

Year: 2023

Color: red

Electric: true

🔹 Using Object.keys(), Object.values(), Object.entries()

Modern methods to work with object data:

let book = {
    title: "JavaScript Guide",
    author: "John Smith",
    pages: 350,
    published: 2023
};

// Get all property names
console.log("Property names:");
console.log(Object.keys(book));

// Get all property values
console.log("Property values:");
console.log(Object.values(book));

// Get key-value pairs
console.log("Key-value pairs:");
console.log(Object.entries(book));

// Display using forEach
console.log("Using forEach:");
Object.entries(book).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

Console Output:

Property names:

["title", "author", "pages", "published"]

Property values:

["JavaScript Guide", "John Smith", 350, 2023]

Key-value pairs:

[["title", "JavaScript Guide"], ["author", "John Smith"], ["pages", 350], ["published", 2023]]

Using forEach:

title: JavaScript Guide

author: John Smith

pages: 350

published: 2023

🔹 JSON.stringify() for Display

Convert objects to JSON strings for easy display:

let product = {
    id: 101,
    name: "Wireless Headphones",
    price: 99.99,
    inStock: true,
    categories: ["Electronics", "Audio"],
    specs: {
        battery: "20 hours",
        wireless: true
    }
};

// Basic JSON string
console.log("Basic JSON:");
console.log(JSON.stringify(product));

// Formatted JSON (with indentation)
console.log("Formatted JSON:");
console.log(JSON.stringify(product, null, 2));

// JSON with specific properties only
console.log("Filtered JSON:");
console.log(JSON.stringify(product, ["name", "price", "inStock"], 2));

Console Output:

Basic JSON:

{"id":101,"name":"Wireless Headphones","price":99.99,"inStock":true,"categories":["Electronics","Audio"],"specs":{"battery":"20 hours","wireless":true}}

Formatted JSON:

{
  "id": 101,
  "name": "Wireless Headphones",
  "price": 99.99,
  "inStock": true,
  "categories": [
    "Electronics",
    "Audio"
  ],
  "specs": {
    "battery": "20 hours",
    "wireless": true
  }
}

🔹 Displaying Objects in HTML

Show object data in web pages:

<!-- HTML -->
<div id="person-info"></div>
<div id="person-list"></div>

<script>
let person = {
    name: "Sarah Johnson",
    age: 30,
    profession: "Web Developer",
    skills: ["JavaScript", "React", "Node.js"]
};

// Display in HTML element
document.getElementById("person-info").innerHTML = 
    `<h3>${person.name}</h3>
     <p>Age: ${person.age}</p>
     <p>Profession: ${person.profession}</p>`;

// Display array property as list
let skillsList = person.skills.map(skill => `<li>${skill}</li>`).join('');
document.getElementById("person-list").innerHTML = 
    `<h4>Skills:</h4><ul>${skillsList}</ul>`;
</script>

HTML Output:

Sarah Johnson

Age: 30

Profession: Web Developer

Skills:

  • JavaScript
  • React
  • Node.js

🔹 Creating a Display Method

Add a custom method to display object information:

let employee = {
    id: 1001,
    name: "Michael Brown",
    department: "Engineering",
    salary: 75000,
    
    // Custom display method
    display() {
        return `Employee: ${this.name} (ID: ${this.id})
Department: ${this.department}
Salary: $${this.salary.toLocaleString()}`;
    },
    
    // Method for HTML display
    toHTML() {
        return `<div class="employee-card">
                  <h3>${this.name}</h3>
                  <p>ID: ${this.id}</p>
                  <p>Department: ${this.department}</p>
                  <p>Salary: $${this.salary.toLocaleString()}</p>
                </div>`;
    }
};

console.log(employee.display());
console.log(employee.toHTML());

Console Output:

Employee: Michael Brown (ID: 1001)
Department: Engineering
Salary: $75,000

<div class="employee-card">
<h3>Michael Brown</h3>
<p>ID: 1001</p>
<p>Department: Engineering</p>
<p>Salary: $75,000</p>
</div>

🧠 Test Your Knowledge

Which method converts an object to a formatted JSON string?