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"
}
- Stores data in key-value format
- Example:
name → "Anil Sidhu"
Display Object Data on UI
Step
- 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:
getElementById()→ selects the UI elementinnerHTML = ""→ clears old datafor...inloop → iterates over object keys- 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">
- First input → key
- 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:
- Get input values
- Add new property using:
userDetails[key] = value;
- Call display function again to update UI
Button to Trigger Function
<button onclick="addNewData()">Add New Data</button>
- Calls function on click
- Adds data and updates UI
Initial Display
displayObjectData();
- Runs function when page loads
- Shows default object data
Flow of Execution
- Page loads → object data displayed
- User enters key and value
- Clicks button
- Data added to object
- UI updates automatically
Important Concepts
- Objects store data in key-value format
for...inloop is used for objectsinnerHTMLupdates UI dynamically- Object properties can be added dynamically
Common Mistakes
- Using
for...ofinstead offor...infor objects - Not clearing
innerHTML(causes duplicate data) - 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);
- More efficient and safer