Reputation: 15
so, I have made use of the fetch API to...
The JSON File: roughly like this: [["hello.css", "world.css", "why.css"], "doesn't.css", "this.css", "work.css"]
The Conditions: if there is a big Group of Strings in an array, inside the array, then turn that into a <optgroup>.
Where it Fails: in the Initialization of the first forEach function.
fetch('./themes.json').then(theResponse => {
let themesJSON = theResponse.text();
console.log(themesJSON); /* All "console.log()" functions are for debugging purposes */
themesJSON.forEach(elm => {
let the = '';
if (elm.length > 1) {
let optgroup = document.createElement('optgroup');
elm.forEach(elm => {
let opt = document.createElement('option');
opt.value = elm;
opt.innerText = elm;
optgroup.insertAdjacentElement('beforeend', opt);
console.log(opt);
})
the.insertAdjacentElement("beforeend", optgroup)
console.log(optgroup);
} else {
let opt = document.createElement('option');
opt.value = elm;
opt.innerText = elm;
the.insertAdjacentElement('beforeend', opt);
console.log(opt);
}
document.getElementById('themeSelection').insertAdjacentElement("beforeend", the);
console.log(the);
});
})
Upvotes: 1
Views: 403
Reputation: 199
You are using:
let themesJSON = theResponse.text();
which returns a promise that resolves to a string.
What you need is JavaScript representation of your JSON file.
For that the correct syntax would be like this:
fetch('./themes.json')
.then(theResponse => theResponse.json())
.then(actualArray => {
console.log(actualArray)
})
Upvotes: 2