I have an object with 4 properties that i want to make to a list using only JS. Could someone help me to see what is wrong with my code? I can't seem to get it to render..
const categoriesOb = {
animals: ["rabbit", "horse", "dog", "bird"],
cities: ["malmö", "umeå", "köping", "örebro"],
fruits: ["banana", "apple", "orange", "pear"],
movies: ["frost", "jaws", "batman", "avatar"],
};
function makeUl(object) {
const catList = document.createElement("ul");
for (let i = 0; i < object.length; i++) {
const catBtn = document.createElement("li");
catBtn.className = "catBtn";
catBtn.appendChild(document.createTextNode(object[i]));
catList.appendChild(catBtn);
}
return catList;
}
document.getElementById("category-container").appendChild(makeUl(categoriesOb));
<div id="category-container"></div>
Object.keys()
is what you want here.
Also, using the for...of
construct means you won't need to mess around with pointer variables and iterator length.
const categoriesOb = {
animals: ['rabbit', 'horse', 'dog', 'bird'],
cities: ['malmö', 'umeå', 'köping', 'örebro'],
fruits: ['banana', 'apple', 'orange', 'pear'],
movies: ['frost', 'jaws', 'batman', 'avatar'],
};
function makeUl(object) {
const catList = document.createElement('ul');
for (let property of Object.keys(object)) {
const catBtn = document.createElement('li');
catBtn.className = 'catBtn';
catBtn.appendChild(document.createTextNode(property));
catList.appendChild(catBtn);
}
return catList;
}
document.getElementById('category-container').appendChild(makeUl(categoriesOb));
Hope this helps.