Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this.

Here is my current code:

let myObj = [
  {name: "Harry Potter", author: "JK Rowling"},
  {name: "Hunger Games", author: "Suzanne Collins"},
  {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
  {name: "Game of Thrones", author: "George R.R. Martin"},
  {name: "Percy Jackson", author: "Rick Riordan"},
];

console.log(myObj);

let myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");
document.getElementById("myDiv").appendChild(myUL);
for (const item of myObj) {
   document
   .getElementById("myUL")
   .appendChild(document.createElement("LI"));
}
<div id="myDiv"></div>

Struggling to format my list to look like this:

  • JK Rowling: Harry Potter
  • Suzanne Collins: Hunger Games
  • J. R. R. Tolkien: Lord of the Rings
  • George R.R. Martin: Game of Thrones
  • Rick Riordan: Percy Jackson

Any tips on accomplishing this using vanilla JS would be appreciated!

Answer №1

To create a <strong> tag containing item.author, it's recommended to utilize the createElement method.

You can then generate a new text node for item.name by using document.createTextNode.

Finally, attach the textNode to the li element and append it to the ul:

const myObj = [
  {name: "Harry Potter", author: "JK Rowling"},
  {name: "Hunger Games", author: "Suzanne Collins"},
  {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
  {name: "Game of Thrones", author: "George R.R. Martin"},
  {name: "Percy Jackson", author: "Rick Riordan"},
];

const myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");

const ul = document.getElementById("myDiv").appendChild(myUL);

for (const item of myObj) {
    let author = document.createElement("strong");
    author. textContent = item.author + ': ';
    
    let li = document.createElement("li");    
    li.appendChild(author);
    li.appendChild(document.createTextNode(item.name))
    
    ul.appendChild(li);
}
<div id="myDiv"></div>

Answer №2

If you need to customize your unordered list, make the necessary changes in the JavaScript code below:

let myList = [
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { title: "To Kill a Mockingbird", author: "Harper Lee" },
  { title: "1984", author: "George Orwell" },
  { title: "Brave New World", author: "Aldous Huxley" },
];

let ulElement = document.createElement("ul");
ulElement.setAttribute("id", "myList");

for (const item of myList) {
  let liItem = document.createElement("li");
  liItem.textContent = `${item.author}: ${item.title}`;
  ulElement.appendChild(liItem);
}

document.getElementById("listContainer").appendChild(ulElement);

In this updated script, individual list items are created and added to the unordered list element. To display titles in bold format, you can utilize <strong> or <b>

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

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

Is it possible to utilize the addition assignment operator (`+=`) to modify the `transform:rotate('x'deg);` CSS property using

This is the code I have been working on: #move{ height:70px; width:70px; border:2px solid black; border-radius:15px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="button" val ...

What is the proper way to incorporate a ref within a class component?

I am encountering an issue with my class component. I'm wondering if there is a comparable feature to useRef() in class components? Despite several attempts at researching, I have yet to find a solution. ...

Is forwardRef not explicitly exported by React?

UPDATE: The issue with the code implementation below has been resolved. It was discovered that the error was caused by a react-redux upgrade, as redux now requires functional components instead of class components. import React, { forwardRef } from ' ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

Selenium and Python: Dealing with the ElementNotInteractableException when trying to input a value in a td element

My attempt to input the number 1 into the MasterPack boxes in this table is met with an error indicating that it is not interactable. https://i.sstatic.net/J79p6.png I encountered the "element not interactable" error while using the following code: driver ...

ReactJS input range issue: Cannot preventDefault within a passive event listener invocation

I've been encountering some issues with the react-input-range component in my React App. It functions perfectly on larger viewports such as PCs and desktops, but on smaller devices like mobile phones and tablets, I'm seeing an error message "Unab ...

Utilize Vue.js and express.js to distribute HTML files securely

Currently, my tech stack includes Vue.js for the frontend and Express.js for the backend. When I kick off the express.js server using npm start, my goal is to serve the Vue frontend component. By utilizing the Vue generator and Express generator, I attemp ...

What is the best way to find the maximum and minimum values within a JSON object that is populated from user inputs using only JavaScript?

Here is a simple form that stores data at the following link: https://jsfiddle.net/andresmcio/vLp84acv/ var _newStudent = { "code": code, "names": names, "grade": grades, }; I'm struggling to retrieve the highest and lowe ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

Limit access to route in ExpressJS only to internal redirects

I'm managing an ExpressJS application that includes specific routes which I intend to only function when redirected to from my code, rather than input directly into the URL. Essentially, if a user attempts to enter "myapp.com/url" it should not be ac ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Retrieve the dynamically generated element ID produced by a for loop and refresh the corresponding div

I am facing a challenge with my HTML page where I generate div IDs using a for loop. I want to be able to reload a specific div based on its generated ID without having to refresh the entire page. Here is a snippet of my HTML code: {% for list in metrics ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

Decrease the dimensions of the image while maintaining its width at 100%

I've got a dilemma with the images on my website that are linked from image hosting sites. They all need to be displayed at 100% width, but some of them have huge pixel dimensions which cause slow loading times. Is there a way to resize the images wi ...

Looking to achieve a scroll effect with mix-blend-mode using JavaScript?

I am seeking a method to adjust the background color of a specific element based on the background itself. While CSS offers the mix-blend-mode property, I am looking to specify the color manually. Ideally, I would like to achieve the same effect using an ...

Exploring the functionality of Radar Chart within a React component

Within the index.html file that is being utilized, there exists a javascript code specifically designed for the chart function. <script src="js/plugins/chartJs/Chart.min.js"></script> var radarData = { labels: ["In Perso ...

Having trouble with Angular ngRoute functionality?

I'm currently working on configuring a basic Angular app. Here is my main HTML: <html ng-app="CostumerApp"> <head> <title> Customers </title> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstr ...

Convert the JSON data into the specified format using JavaScript

Is there a way to transform JSON data like this in JavaScript? data = [{acquired: "2018-03-09T22:49:52.935Z", mean_ndvi: -0.0483685} {acquired: "2018-02-13T22:49:16.568Z", mean_ndvi: 0.00595065} {acquired: "2018-04-01T22:50:30.912Z", mean_ndvi: -0.033455} ...