Home > Net >  How to loop an Multidimentional Object-Array then create a HTML Nested List?
How to loop an Multidimentional Object-Array then create a HTML Nested List?

Time:06-23

var array = {
'Brazilians': ['Thalison', 'Allan'],
'Venezuelans': ['Jaime', 'Andres'],
 }

I just learned how to display the array with this:

 for (key in array) {

      document.write(`${key}: ${array[key]}<br>`);

      console.log(`${key}: ${array[key]}`);
 }

I hope to get this result with

    <ul>
    <li>
        Brazilians
        <ul>
            <li>Thalison</li>
            <li>Allan</li>
        </ul>.....

CodePudding user response:

var array = {
  'Brazilians': ['Thalison', 'Allan'],
  'Venezuelans': ['Jaime', 'Andres'],
}

const createItem = (text) => {
       const li = document.createElement('li')
      li.innerText = text;
      return li
}

 for (key in array) {
    const ul = document.createElement('ul')
    const li = createItem(key)
    li.style.fontWeight = 'bold'
    ul.append(li)
    array[key].forEach(item => { 
      const li = createItem(item)
      ul.append(li)
    })
    document.body.append(ul)
 }

CodePudding user response:

First of: never use document.write. Even the documentation recommends against using it and gives some reason to why you shouldn't use it.


One way to create HTML in JavaScript is with document.createElement(). This function can create HTML elements, which you can then append to the DOM with the append() method that every HTML Element has.

In the example below I've used a for...of loop in combination with Object.keys(). While for...in can be used to iterate over objects, the for...of loop is recommended as it only loops over values that should be looped over. See the difference here.
Object.keys() turn all the property keys into an array of keys. So the result in this case would be ['Brazilians', 'Venezuelans'] where we in turn loop over.

Inside the loop we create a second loop where we loop over the names array of each property in the object.

var data = {
  'Brazilians': ['Thalison', 'Allan'],
  'Venezuelans': ['Jaime', 'Andres'],
}

// First create the outer list.
const list = document.createElement('ul');

// Loop over the keys of the object.
for (let key of Object.keys(data)) {
  // Create a list item for every key.
  const listItem = document.createElement('li');
  listItem.textContent = key;
  
  // Create the sub list.
  const subList = document.createElement('ul');
  
  // Loop over the nested array.
  for (let name of data[key]) {
    // Create a sub list item for every name.
    const subListItem = document.createElement('li');
    subListItem.textContent = name;
    
    // Add the sub list item to the sub list.
    subList.append(subListItem);
  }
  
  // Add the sub list to the list item.
  listItem.append(subList);
  
  // Add the list item to the list.
  list.append(listItem);
}

// Add the list to the body.
document.body.append(list);

  • Related