Implement a JavaScript loop that operates within an array contained within an object's array

I possess an array of objects containing information, these pieces of info are string numbers array

My aim is to create a function that iterates through all this info and displays the sector name. Below the sector name, for each specific <li>, the licenseTitle should be printed.

The issue arises when I attempt to achieve this, as my loop prints all the licenseTitle in the database under the first sector name instead of how I intend.

The desired output format would be:

tourism

. tourism 1

. tourism 2

education

. education 1

. education 2

Is there a way I can accomplish this?

const database = [{
        sectorId: 1,
        sectorName: "tourism",
        sectorIcon: "icon-1.png",
        sectorN: "tourism",
        licenseTitle: ["tourism 1", "tourism 2"],
        licenseNum: ["7960", "7961"]
    },
    {
        sectorId: 2,
        sectorName: "education",
        sectorIcon: "icon-2.png",
        sectorN: "education",
        licenseTitle: ["education 1", "education 2"],
        licenseNum: ["7950", "7951"]
    }
  ]

// Printing all sectors' titles with the corresponding license title and description
function AllSectors(){
    for(let i = 0; i < database.length; i++){
        document.querySelector('.content-right').innerHTML += `
            <div class="box">
                <div class="box-title">
                    <div class="title">
                        <input type="checkbox" value="${database[i].sectorN}" class="checktitle" name="sectorCheck">
                        ${database[i].sectorName}
                    </div>
                    <div class="arrow">
                         <i class="fas fa-angle-down"></i>
                     </div>
                </div>
                <div class="box-details">
                    <ul class="details-list">`;
                    for(let j = 0; j < database[i].licenseTitle.length; j++){
                        document.querySelector('.details-list').innerHTML += `
                        <li><a href="#">${database[i].licenseTitle[j]}</a></li>
                        `;
                    }
                    `</ul>
                </div>
            </div>
        `;
    }
}

AllSectors();
<div class="content-right"></div>

Answer №1

You have the ability to nest template literals within your code.

document.querySelector('.content-right').innerHTML = database
  .map(db => `
  <div class="box">
    <div class="box-title">
      <div class="title">
        <label>
          <input type="checkbox" value="${db.sectorN}" class="checktitle" name="sectorCheck">
          ${db.sectorN}
        </label>
      </div>
      <div class="arrow">
        <i class="fas fa-angle-down"></i>
      </div>
    </div>
    <div class="box-details">
      <ul class="details-list">${db.licenseTitle
        .map(lT=>`<li><a href="#">${lT}</a></li>`).join("")}
      </ul>
    </div>
  </div>`).join("");
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"  />

<div class="content-right"></div>
<script>
  const database = [{
      sectorId: 1,
      sectorName: 'tourism',
      sectorIcon: 'icon-1.png',
      sectorN: 'tourism',
      licenseTitle: ['tourism 1', 'tourism 2'],
      licenseNum: ['7960', '7961'],
    },
    {
      sectorId: 2,
      sectorName: 'التعليم',
      sectorIcon: 'icon-2.png',
      sectorN: 'education',
      licenseTitle: ['education 1', 'education 2'],
      licenseNum: ['7950', '7951'],
    },
  ];
</script>

Answer №2

Implement a function specifically for generating the list

const dataEntries = [{
    sectorId: 1,
    sectorName: 'tourism',
    sectorIcon: 'icon-1.png',
    sectorN: 'tourism',
    licenseTitle: ['tourism 1', 'tourism 2'],
    licenseNum: ['7960', '7961'],
  },
  {
    sectorId: 2,
    sectorName: 'التعليم',
    sectorIcon: 'icon-2.png',
    sectorN: 'education',
    licenseTitle: ['education 1', 'education 2'],
    licenseNum: ['7950', '7951'],
  },
];

// Display all sectors with their respective titles and descriptions
function AllSectors() {
  for (let i = 0; i < dataEntries.length; i++) {
    const str = `
          <div class="box">
              <div class="box-title">
                  <div class="title">
                      <input type="checkbox" value="${dataEntries[i].sectorN}" class="checktitle" name="sectorCheck">
                      ${dataEntries[i].sectorName}
                  </div>
                  <div class="arrow">
                       <i class="fas fa-angle-down"></i>
                   </div>
              </div>
              <div class="box-details">
                  <ul class="details-list">${generateList(dataEntries[i])}</ul>
              </div>
          </div>`;
    document.querySelector('.content-right').innerHTML += str;
  }
}

AllSectors();

function generateList(dataEntries) {
  let output = '';
  for (let j = 0; j < dataEntries.licenseTitle.length; j++) {
    output += `<li><a href="#">${dataEntries.licenseTitle[j]}</a></li>`;
  }
  return output;

}
<div class="content-right"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate the ability to print charts exclusively on HighCharts

I am currently working with a DotNetHighchart that has features like Print Chart, Download as PDF, etc. My goal is to remove only the print chart option. In earlier versions of Highcharts, this was easily achieved by using: .SetExporting(new Exporting { ...

Why doesn't Select2 function properly in Bootstrap 3 when the tabindex is removed?

There is a bug with Select2 that causes it to malfunction in a Bootstrap 3 modal unless the tabindex element is removed. I have successfully resolved this issue in several modals on my page, but one specific modal still cannot get Select2 to function. Eac ...

Is it possible for a recursive function in expressjs to return an empty array?

I am working on extracting all child elements from MongoDB using a recursive function. The function loops through all the values and successfully logs them when pushed to an array. However, I am facing an issue where the returned array is empty. This cod ...

How to rotate an object in Threejs using the mouse without having to click and drag?

I'm searching for a solution to rotate around an object in Threejs without the need to hold down the mouse button. A good example can be found on this website: which utilizes Threejs. Despite searching through forums and documentation, I have been un ...

Exploring the Force-Directed Graph Demo on bl.ocks.org

I don't have much expertise in javascript, jquery, or json. My objective is to create a graph using the force-directed graph example from bl.ock.us. 1) I wrote a python script to generate the necessary json data. 2) I noticed others were us ...

What is the best way to give precedence to non-auto capitalization in input fields on the Input Component from Material UI, especially when using iPads?

The issue I'm encountering is specific to Material UI and IPad, requiring a change in the component used from MUI. Currently, I am utilizing the Input component from Material UI. Upon clicking on the input, the IPad keyboard opens and automatically ...

A significant decrease in speed is noticeable when Raphael JS is utilized with a large number of rectangles with backgrounds

I am faced with a challenge involving a large collection of small rectangles (4K-5K) and I am looking to implement the sprite technique in order to assign them a background using just one image to avoid overwhelming the server with requests. When I opt fo ...

Pass the identifier to another component in Vue

Connecting with the Community Within my application, I showcase a list of doctors in the DoctorView component using the following code: <div class="col-12 m-2" v-for="recommendation in recommendations" :key="recommend ...

The error message "Unexpected token" occurs when using async function prefix in TypeScript

Encountering an 'Unexpected token' issue in typescript while attempting to create an async function: async function test() { ... } Investigated the possibility of this error being caused by running an outdated version of node that doesn' ...

Is there a way to input data into an AngularJS modal?

I'm looking for some assistance : How do I go about loading data into the content of an angular modal? Is there a way to load custom data for a selected item? ............................................................. This is the code ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

preventing sliding in a specific angle within the angularjs ionic framework

I am completely new to angularjs and embarking on my very first app creation journey with the ionic framework. The initial step I took was to generate an ionic app using this command: $ ionic start myApp sidemenu The creation of the app went smoothly, co ...

Implementing a password toggle feature on a form that extends Django's default Authentication Form

Incorporating a password toggle feature has become quite the challenge as I extend Django's AuthenticationForm to create my UserLoginForm. Attempting to implement this feature has proven difficult, especially since I have been unable to make use of th ...

Determining whether a PFUser is being created or updated with the AfterSave function

Struggling to differentiate between whether a PFUser is being updated or saved for the first time? I tried implementing a solution from parse.com here, but it's not working as expected. No matter what, I always end up with a false value, be it an init ...

Updating documents in MongoDB can involve $push-ing multiple objects and $pop-ing multiple objects in a single update operation

Consider a scenario where you have a MongoDB document containing an array of 100 objects that you want to maintain at a fixed length of 100. Upon receiving a batch of new objects, you need to update the array by adding the new objects while removing an equ ...

Using Javascript to retrieve the selected value from a dropdown menu does not return any results

Struggling to retrieve the selected value from a drop-down list using JavaScript? Even when an item is chosen, do you keep getting 'null' as the result? Let's take a look at the HTML page: <select class="mySelect"> <option val ...

Incorporate various inputs into a nested array

I am interested in structuring an array of information. Each piece of information includes a title object with translations in 3 different languages, along with multiple values that are also multilingual. While referencing this question, I successfully im ...

Loop through the JSON data to obtain distinct values for certain indices

My PHP script retrieves data with the following query: SELECT objective,signal_type,signal_name FROM signals WHERE channel="Email" This is how the data is returned: [ { "objective": "Awareness", "signal_type": "Efficiency", " ...

Trigger a callback in KnockoutJS once all bindings have been successfully set up

I am facing a frustrating bug that is detailed here: <select> only shows first char of selected option and I am looking for a solution to remove the display:none from my select boxes in order to resolve this issue. Any ideas? Here's the binding ...

Utilize text instead of visual aids - Engaging javascript trivia game

I have successfully implemented a 10-question trivia game with a timer in html, javascript, and css. The game currently displays images from a folder and offers 4 answer options. However, I am looking to switch from using images to serving text-based ques ...