I need to display data from a JSON file in select options, and here is the structure of my JSON file:
[{
"vehicle": "car1",
"type": [
{"name" : "BMW",
"details" : [{
"color" : "red",
"price" : "50000"
},
{
"color" : "blue",
"price" : "51000"
}]}
]},
{
"vehicle": "car2",
"type": [
{"name" : "Lambo",
"details" : [{
"color" : "green",
"price" : "150000"
},
{
"color" : "yellow",
"price" : "151000"
}]}
]}
]
In order to populate values into two select elements, I implemented a loop in my code:
for (i = 0; i < data.length; i++) {
select1.insertAdjacentHTML('beforeend', `
<option>${data[i].vehicle}</option>
`)
for (j = 0; j < data[i].type.length; j++) {
for (k = 0; k < data[i].type[j].details.length; k++) {
select2.insertAdjacentHTML('beforeend', `
<option">${data[j].type[j].details[k].color}</option>
`)
}
}
This should create the following selection options:
- Car1
- Car2
And for the second select element:
- Red / Green
- Blue / Yellow
Based on the first selection option. However, there seems to be an issue with duplicate entries in the second select, as it's showing 4 items instead of just 2.
If anyone can assist me with this problem, I would greatly appreciate it. Thank you!
var json_obj = [{
"vehicle": "car1",
"type": [
{"name" : "BMW",
"details" : [{
"color" : "red",
"price" : "50000"
},
{
"color" : "blue",
"price" : "51000"
}]}
]},
{
"vehicle": "car2",
"type": [
{"name" : "Lambo",
"details" : [{
"color" : "green",
"price" : "150000"
},
{
"color" : "yellow",
"price" : "151000"
}]}
]}
];
function apply_change(data) {
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
for (i = 0; i < data.length; i++) {
select1.insertAdjacentHTML('beforeend', `
<option>${data[i].vehicle}</option>
`)
for (j = 0; j < data[i].type.length; j++) {
for (k = 0; k < data[i].type[j].details.length; k++) {
select2.insertAdjacentHTML('beforeend', `
<option">${data[j].type[j].details[k].color}</option>
`)
}
}
}
}
apply_change(json_obj);
select 1: <select id="select1"></select>
select 2: <select id="select2"></select>