Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my list not created in javascript?

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? And in the long run i want to have a function that when a user select one of the categories it randomly chooses a value.

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading