My head was overheated today.. I need help with my code. My English is not so good, so it's hard to explain my issue. So I put problem in HTML what kind of style I need to get from JS. Added things.json
file as example, and added 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>
There's example of things.json
file:
[
{
"thing": "table",
"color": [
"brown",
"black",
"white"
]
}
{
"thing": "chair",
"color": [
"yellow",
"black",
"blue"
]
}
{
"thing": "bed",
"color": [
"red",
"blue",
"green"
]
}
]
There is 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 }
Assuming your json is an array of objects (with colors) you would need 2 levels of loops. One for every item (object) in the array. The other for each object to build the list from its colors (that's also an array).
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.