What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the things.json file along with some JS code.

<!-- What I'm getting: -->

<h2>Table</h2>

<ul>
  <li>brown, black, white</li>
</ul>


<!-- What I need to get: -->

<h2>Table</h2>

<ul>
  <li>brown</li>
  <li>black</li>
  <li>white</li>
</ul>

Here's an example of the things.json file:

[
 {
  "thing": "table",
  "color": [
   "brown",
   "black",
   "white"
   ]
  }
  {
  "thing": "chair",
  "color": [
   "yellow",
   "black",
   "blue"
   ]
  }
  {
  "thing": "bed",
  "color": [
   "red",
   "blue",
   "green"
   ]
  }
]

Lastly, here's an example of my function:

 const ENDPOINT = 'things.json' 

    async function getThing(url) { 
      const resp = await fetch(url) 
      const data = await resp.json() 
      data.forEach(appendToHtml) return data 
} 

getThing(ENDPOINT).then((value) => { console.log('getThings', value) }) 

    function appendToHtml(data) {
        const divEl = document.createElement('div')
        const h2El = document.createElement('h2')
        const liEl = document.createElement('li')
        h2El.textContent = data.thing
        liEl.textContent = data.color
        outputEl.append(divEl)
        divEl.append(h2El)
        divEl.append(liEl)

        return divEl
    }

Answer №1

To effectively parse through your JSON data, which consists of an array of objects containing colors, you will need to implement a dual-level loop structure. The first loop iterates through each item (object) in the array, while the second loop within it processes the colors associated with each object.

var arr = [{
  "thing": "table",
  "color": [
    "brown",
    "black",
    "white"
  ]
}, {
  "thing": "chair",
  "color": [
    "yellow",
    "black",
    "blue"
  ]
}, {
  "thing": "bed",
  "color": [
    "red",
    "blue",
    "green"
  ]
}];

var outputEl = document.body;

function appendToHtml(data) {
  const divEl = document.createElement('div')
  const h2El = document.createElement('h2')
  const list_container = document.createElement('div')
  h2El.textContent = data.thing
  outputEl.append(divEl)
  divEl.append(h2El)
  divEl.append(list_container)
  list_container.innerHTML = appendToList(data.color);
  return divEl
}

function appendToList(colors) {
  return "<ul>" + colors.map(color=>`<li>${color}</li>`).join("\n") + "</ul>"
}

arr.forEach(function(obj) {
  appendToHtml(obj)
})
<body>
    
</body>

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

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...

"Despite successfully retrieving data from the JSON response, a null pointer exception is still being

Currently, I am attempting to fetch data by invoking web services using an AsyncTask class. Upon receiving a successful JSON response as shown in the screenshot, the application crashes within the listener.onTaskCompletedObject(responseJson); method inside ...

JavaScript popup is no more visible on the webpage

Recently, I implemented a pop-up on my website that used cookies to prevent it from appearing every time a user visited a page. However, after making this change, the pop-up stopped showing altogether. Despite my best efforts in testing, researching, and s ...

Generating a list of objects from an array of strings

I am currently facing an issue in my code and I could use some help with it. Below are the details: I have a array of string values containing MAC addresses and constant min & max values. My goal is to map over these MAC values and create an array of obje ...

Outputting information from a multi-level array

I am facing a challenge in looping through an array retrieved from a database and displaying the Field_Name and Field_Value on a webpage. Array ( [0] => stdClass Object ( [Field_Name] => First Name [Field_Value] = ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

Issue with OpenLayers Icon not appearing on screen

I just finished creating a SpringBoot app using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and packaging it as an executable JAR file. Within this app, I have integrated OpenLayers 4 library to display a map with an Icon. Howeve ...

Transforming PHP JSON into JavaScript with getJSON

Hello everyone, I must admit my lack of knowledge in javascript/ajax as I am struggling to convert this php json into a javascript function $json = file_get_contents('http://videoapi.my.mail.ru/videos/mail/alex.costantin/_myvideo/4375.json'); ...

Utilizing an array of objects without specified indexes

I am currently taking a class on factory workers and another one on factory products. While that's all good, I now want to develop a program in main() that prompts the user to input information about either a worker or a new product in the factory, us ...

Logging in Python: A Guide to JSON Formatting

Our Python Django application requires logging using the code snippet below in order to allow ELK to index the log record as JSON logger.info(json.dumps({'level':'INFO','data':'some random data'}) We currently have ...

Having trouble with a Pandas DataFrame - looking to filter by a JSON key that contains a date

I'm looking to filter this JSON data by date, but I'm struggling to figure out how. I've attempted different methods found online without success. Any help would be greatly appreciated. Below is my code snippet. import urllib.request import ...

Serialization of HTML string into JSON format

While working in a Razor View, I encountered the following line: @Html.Raw(Json.Encode(new { tag = "<br />" })); This code snippet replaces HTML tags and generates the response: {"tag":"\u003cbr /\u003e"}; However, my desired output is: ...

What is the best way to implement jQuery on my website?

Instead of copying all the example code here, you can check out the jQuery demo page: Demo Page I would like to integrate the Latest News example with scrolling text in red from the demo page into my website. The demo page also provides links to the sour ...

"PhpStorm's formatting feature automatically indents multiline arrays with a double tab

Issue: When using PhpStorm(10), arrays are formatted with double indentation instead of single. Expected formatting: public function behaviors () { return [ [ 'class' => NestedSetsBehavior::className() ] ]; ...

Attempting to insert an element after the .load event has been triggered

I have been attempting to update the contents of ".myShop" after it's loaded from an external XML file, but without success. I believe my timing is correct, but I suspect that a loaded element may not be part of the DOM? Here's what I'm exp ...

Addressing the issue of pm2 with netmask 1.0.6 posing a serious security risk

While working on my project, I encountered a problem in the terminal when using the pm2-runtime command for the runtime environment. When running the command npm i, I received warnings at two levels: High netmask npm package vulnerable to octa ...

What are the advantages of choosing express.js over Ruby on Sinatra?

Currently brainstorming for a social app and contemplating the switch from my initial option, Sinatra/Ruby to express.js/nodejs. My main focus is on the abundance of open source projects in Ruby that can expedite development. Another major consideration i ...

What is the correct way to pass data to a sibling component while making sequential asynchronous calls?

Currently, I am developing a hackernews clone in order to practice my ReactJS skills. Initially, I am constructing it solely with React and intend to integrate Redux at a later stage. Here is the component structure of the project: --main |--menubar | ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...