Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness?
<div id="accordion" class="display-data">
<!-- AJAX displays here -->
</div>
Is there a better approach for achieving the desired outcomes using this JavaScript data?
myObj = [
{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford",
"models":[
"Fiesta",
"Focus",
"Mustang"
],
},
{
"name":"BMW",
"models":[
"320",
"X3",
"X5"
],
},
{
"name":"Fiat",
"models":[
"500",
"Panda"
],
}
]
},
{
"name":"Matthew",
"age":32,
"cars": [
{ "name":"Ford",
"models":[
"Everest",
"WRanger",
"Mustang"
],
"colour": "Red2"
},
{
"name":"BMW",
"models":[
"Z Series",
"X2000",
"X5"
],
"colour": "Green2"
},
{
"name":"Toyota",
"models":[
"Camary",
"Tarago"
],
"colour": "Blue2"
}
]
}
]
var myObj, i, j, k, str = "";
for (i = 0; i < myObj.length; i++) {
str += "<h1>" + myObj[i].name + "</h1>";
str += " <ul>";
for (j in myObj[i].cars) {
str += " <li>" + myObj[i].cars[j].name + "";
str += " <ul>";
for (k in myObj[i].cars[j].models) {
str += " <li>" + myObj[i].cars[j].models[k] + "</li>";
}
str += " </ul>";
str += " </li>";
}
str += " </ul>";
}
document.getElementById("accordion").innerHTML = str;
I have combined objects and arrays, it works but I'm unsure if there's a more optimal method.
https://jsfiddle.net/ok6570m2/1/#&togetherjs=GMGBdGE6pE
I don't have much knowledge about JavaScript and arrays.