Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness?

    <div id="accordion" class="display-data">
    <!-- AJAX displays here -->
    </div>

Is there a better approach for achieving the desired outcomes using this JavaScript data?

myObj = [
    {
        "name":"John",
        "age":30,
        "cars": [
            { "name":"Ford", 
                "models":[ 
                    "Fiesta", 
                    "Focus", 
                    "Mustang" 
                ],
            },
            { 
            "name":"BMW", 
                "models":[ 
                    "320", 
                    "X3", 
                    "X5"
                ],
            },
            { 
                "name":"Fiat", 
                "models":[ 
                    "500", 
                    "Panda" 
                ],
            }
        ]
    },
    {
        "name":"Matthew",
        "age":32,
        "cars": [
            { "name":"Ford", 
                "models":[ 
                    "Everest", 
                    "WRanger", 
                    "Mustang" 
                ],
                "colour": "Red2"
            },
            { 
            "name":"BMW", 
                "models":[ 
                    "Z Series", 
                    "X2000", 
                    "X5"
                ],
                "colour": "Green2" 
            },
            { 
                "name":"Toyota", 
                "models":[ 
                    "Camary", 
                    "Tarago" 
                ],
                "colour": "Blue2" 
            }
        ]
    }
]
      
      
      
var myObj, i, j, k, str = "";

for (i = 0; i < myObj.length; i++) {

  str += "<h1>" + myObj[i].name + "</h1>";
  str += "  <ul>";  

  for (j in myObj[i].cars) {
    str += "    <li>" + myObj[i].cars[j].name + "";
    str += "        <ul>";
    for (k in myObj[i].cars[j].models) {
      str  += " <li>" + myObj[i].cars[j].models[k] + "</li>";
    }
    str += "        </ul>"; 
    str += "    </li>"; 
  }
  str += "  </ul>";
}

document.getElementById("accordion").innerHTML = str;

I have combined objects and arrays, it works but I'm unsure if there's a more optimal method.

https://jsfiddle.net/ok6570m2/1/#&togetherjs=GMGBdGE6pE

I don't have much knowledge about JavaScript and arrays.

Answer №1

One suggestion is to maximize the use of the templating engine provided by your framework, or opt for a reliable templating library if you anticipate working on extensive tasks. However, an alternative approach involves leveraging a template literal for enhanced data parsing readability.

function customizeEntry(entry) {
  let modifiedEntry = `
    <h1>${entry.name}</h1>
    <ul>
      ${entry.cars.map(car => (
        `<li>${car.name} ${car.colour ? `(${car.colour})` : ''}
            <ul>
              ${car.models.map(model => (`<li>${model}</li>`)).join('')}
            </ul>
         </li>`)).join('')}
    </ul>`; 
  
  const customDiv = document.createElement("div"); 
  customDiv.innerHTML = modifiedEntry;
  
  return customDiv;
}

const batch = [
    {
        "name":"John",
        "age":30,
        "cars": [
            { "name":"Ford", 
                "models":[ 
                    "Fiesta", 
                    "Focus", 
                    "Mustang" 
                ],
            },
            { 
            "name":"BMW", 
                "models":[ 
                    "320", 
                    "X3", 
                    "X5"
                ],
            },
            { 
                "name":"Fiat", 
                "models":[ 
                    "500", 
                    "Panda" 
                ],
            }
        ]
    },
    {
        "name":"Matthew",
        "age":32,
        "cars": [
            { "name":"Ford", 
                "models":[ 
                    "Everest", 
                    "WRanger", 
                    "Mustang" 
                ],
                "colour": "Red2"
            },
            { 
            "name":"BMW", 
                "models":[ 
                    "Z Series", 
                    "X2000", 
                    "X5"
                ],
                "colour": "Green2" 
            },
            { 
                "name":"Toyota", 
                "models":[ 
                    "Camary", 
                    "Tarago" 
                ],
                "colour": "Blue2" 
            }
        ]
    }
]
      
      
      
function adjustEntry(entry) {
  let modifiedEntry = `
    <h1>${entry.name}</h1>
    <ul>
      ${entry.cars.map(car => (
        `<li>${car.name} ${car.colour ? `(${car.colour})` : ''}
            <ul>
              ${car.models.map(model => (`<li>${model}</li>`)).join('')}
            </ul>
         </li>`)).join('')}
    </ul>`; 
  
  const entryDiv = document.createElement("div"); 
  entryDiv.innerHTML = modifiedEntry;
  
  return entryDiv;
}

const container = document.getElementById('accordion');

batch.forEach(entry => container.appendChild(adjustEntry(entry)));
<div id="accordion" class="display-data">
</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

The NodeJs and Express API, integrated with Ejs files, encounters a crash when attempting to retrieve data from the database on the second attempt

I've been assigned the task of developing an API that retrieves data from a database and presents it on the frontend. This is my first time working with APIs, and I've encountered some challenges along the way. The database I'm using is call ...

When I attempt to connect to my local MongoDB database, including a specific port in the URI is preventing the connection from being

While testing a connection to a local DB using mongoose and mongodb, I encountered an issue. Whenever I include a port number in the URI passed to mongoose.connect(), I receive a connection refused error. async function connectDB() { const db = await m ...

Why does this vow continue to linger unresolved?

I've been experimenting with a code that involves adding promises to a queue for processing in a non-blocking manner. One code snippet behaves as anticipated while the other doesn't, leaving me puzzled. Problematic Code: const axios = require(&a ...

Populating a HTML document with data retrieved from an AJAX request

I have a button that, when clicked, should display the values of a specific user. The code snippet for this functionality is as follows: HTML Button: <button onclick="return getUserDetails(<? echo $user['id']; ?>)" class="btn btn-xs bt ...

JQuery AJAX responds with an error

I'm attempting to configure an ajax call using JQuery to access a specific URL. The URL I am targeting for the query is Here's what my jQuery code looks like: $.ajax({ url: "http://www.icis.com/rss/publicrss/", type: "GET", dataType: "xml ...

What is a way to perform pre-increment without utilizing the ++I operator?

It is my belief that the code snippet below: i += 1 or i = i + 1 does not have the same effect as ++i. Am I incorrect in this assumption? Is there an alternative method to achieve pre-increment without utilizing the ++ operator? ...

Having difficulty loading data from a JSON object into a React Select dropdown

I am currently struggling with populating a react-select dropdown using a JSON object. Below is the code for reference. Any assistance would be greatly appreciated. import React, { useState, useEffect } from 'react' import Select from 'react ...

The specified instance of 'xxx' cannot be serialized to JSON in Django's UpdateView

After saving the form information, I attempted to edit it using UpdateView. The parameters are sent via AJAX from the view, but an error occurred: "Object of type Form is not JSON serializable". Below are some code snippets related to this issue. models. ...

Enhancing visual appearance with customized look control through the use of setAttribute

I have developed a unique custom look-controls feature and I am trying to integrate it into the scene using 'setAttribute(componentName, data)', but I'm unsure about what parameters to include. Any suggestions? Here is my approach: const s ...

Bot on Discord using Discord.Js that generates unique invites for users

I'm trying to find a way to generate an invite link for users to keep track of invites. The code I have currently is creating the invite for the Bot instead. const channel = client.channels.cache.find(channel => channel.id === config.server.channel ...

iPad2 always displays UIWebView in 'portrait' orientation

I have a sophisticated HTML5 website that includes JavaScript. It is displayed in a UIWebView. The JavaScript on the page is supposed to determine whether the iPad is in Portrait or Landscape mode. Unfortunately, I have encountered an issue. Regardless of ...

What is the best way to determine the number of objects in a list based on

When I deserialize a JSON like this: files = JsonConvert.DeserializeObject<Files>(json); I am trying to count the instances of natives-windows and artifact, so I have used lambda expressions, but I keep getting a NullReferenceException. files.libra ...

Organizing subcategories within a dropdown checklist

I am currently working on a list that utilizes dropdownchecklist and I am looking to create subgroups from the elements in the list. The goal is that by clicking on a subgroup checkbox, it will automatically check all elements associated with it. Below is ...

Securing data in AngularJS $http.post requests: Best practices

While working on $http.post requests for my app's backend, I noticed a security issue. When inspecting the data using tools like firebug in Firefox, I can see all the information being sent. Is it possible for third parties to intercept this data? Th ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Unable to receive acknowledgment from child component within Redux

I am trying to retrieve props from Redux within a child component, but for some reason, {this.props} is showing up as an empty object. While I am successfully using react-redux connect to access the props in the parent component and pass them down to the ...

Can the keypress event be modified within the Google Chrome browser?

My code is functioning in IE but not in Chrome. I am having issues with the event not changing. Is there a different method for achieving this in Chrome, rather than assigning specific values to the charCode, keyCode, and which variables? You can view my ...

What methods can be employed to stop tests from being included in rollup bundles?

I am currently in the process of creating a react component package and I would like to know how to prevent my tests folder from being included in the dist file that is generated by rollup. After running rollup -c, my directory structure looks like this: ...

Enhance the appearance of the navbar on mobile devices by customizing the styling in Bootstrap 5

Hi everyone, this is my first time posting a question here so please be gentle :) I recently implemented a script to change the CSS of my navbar when scrolling. window.addEventListener("scroll", function () { let header = document.querySelector(".navbar") ...

Understanding the process of extracting elements from a list in Python

I extracted some data from a function and now I'm trying to extract specific information like the shape, labels, and domain from this output. [Annotation(shape=Rectangle(x=0.0, y=0.0, width=1.0, height=1.0), labels=[ScoredLabel(62282a1dc79ed6743e731b3 ...