Home Courses Display & Add Object Data on UI - Object with DOM

Display & Add Object Data on UI - Object with DOM

Display object data on the UI (web page)

Add new key-value pairs dynamically

Update UI instantly after adding data


Creating an Object


let userDetails = {
name: "Anil Sidhu",
email: "anil@test.com",
city: "Delhi"
}

  1. Stores data in key-value format
  2. Example: name → "Anil Sidhu"


Display Object Data on UI

Step

  1. Use a <ul> element in HTML

<ul id="user-UL"></ul>


JavaScript Function


function displayObjectData() {
let userEl = document.getElementById('user-UL');
userEl.innerHTML = "";

for (let key in userDetails) {
userEl.innerHTML += "<li>" + key + " is " + userDetails[key] + "</li>";
}
}

Explanation:

  1. getElementById() → selects the UI element
  2. innerHTML = "" → clears old data
  3. for...in loop → iterates over object keys
  4. Displays key and value in list format


Taking Input from User


<input type="text" id="key" placeholder="enter key">
<input type="text" id="value" placeholder="enter value">

  1. First input → key
  2. Second input → value


Add New Data to Object


function addNewData() {
let key = document.getElementById('key').value;
let value = document.getElementById('value').value;

userDetails[key] = value;

displayObjectData();
}

Explanation:

  1. Get input values
  2. Add new property using:

userDetails[key] = value;

  1. Call display function again to update UI


Button to Trigger Function


<button onclick="addNewData()">Add New Data</button>

  1. Calls function on click
  2. Adds data and updates UI


Initial Display


displayObjectData();

  1. Runs function when page loads
  2. Shows default object data


Flow of Execution

  1. Page loads → object data displayed
  2. User enters key and value
  3. Clicks button
  4. Data added to object
  5. UI updates automatically


Important Concepts

  1. Objects store data in key-value format
  2. for...in loop is used for objects
  3. innerHTML updates UI dynamically
  4. Object properties can be added dynamically


Common Mistakes

  1. Using for...of instead of for...in for objects
  2. Not clearing innerHTML (causes duplicate data)
  3. Forgetting to call display function after adding data


Better Practice (Optional Improvement)

Instead of innerHTML +=, use:


let li = document.createElement("li");
li.textContent = key + " is " + userDetails[key];
userEl.appendChild(li);

  1. More efficient and safer


Share this lesson: