-1

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>
Luddepb
  • 15
  • 4
  • What is the problem. I do not see you start what the problem is. – epascarello Nov 28 '22 at 13:40
  • 1
    An object does not have a length. To get the keys of an object, use Object.keys() and you can iterate over that. – epascarello Nov 28 '22 at 13:41
  • What output are you expecting? Every element from every array in the object? Because you only have one for-loop here. – Ivar Nov 28 '22 at 13:41
  • `for (let i = 0; i < object.length; i++)` - You're trying to loop over an object's properties. This isn't done like it is with an array, but it *can be* done. The linked duplicate can help. (Alternatively, you can modify your data structure.) – David Nov 28 '22 at 13:42

1 Answers1

0

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.

damonholden
  • 1,062
  • 4
  • 17
  • Thank you, the for of loop did the trick! – Luddepb Nov 28 '22 at 13:54
  • when doing recursion in JavaScript, I always try to make it work with a `for...of` loop as it is far more readable than doing some kind of pointer variable construct. There are times when you can't do this but I always try to go for readability first. Glad to help regardless. – damonholden Nov 28 '22 at 14:00