G.Colville G.Colville - 16 days ago 5
Javascript Question

Loop through an object and append the properties to an html file

Hi I am new to JavaScript and have been doing some practice stuff. I am struggling with looping through an Object's properties and appending each property to the DOM. Can someone provide some guidance please? I tried piecing this together through other questions but not sure where I am going wrong?

var person = {
firstName: "john",
lastName: "doe",
age: 45,
placeOfBirth: "somewhere"
}

for(var i = 0; i < person.length; i++) {
if(hasOwnProperty(person[i])) {
var p = document.createElement("p");
p.innerHTML = person[i];
document.body.appendChild(p)
}
}

Answer

and you dont need person.hasOwnProperty(key) because key is property only . so it will always be true if you use if condition or not .

var person = {
    firstName: "john",
    lastName: "doe",
    age: 45,
    placeOfBirth: "somewhere"
}

for(var key in person) {
    
        var p = document.createElement("p");
        p.innerHTML = person[key];
        document.body.appendChild(p)
    
}

Comments