Jeeva Raam Jeeva Raam - 1 month ago 11
Javascript Question

JavaScript nested object array, How to loop through the 'KEY' of array?

var myCollection = {
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
for ( x in myCollection ) {
document.getElementById("id1").innerHTML += x + "<br />";
}


Ans : cars

Likewise how can I display the 'KEY' value which is inside the array i.e. 'name' or 'models'

for ( x in myCollection.cars ) {
document.getElementById("id1").innerHTML += x + "<br />";
}


Ans :
0
1
2


Why it returns array index value, How can I display the 'KEY' value 'name' or 'models' ?


Expected Ans:



name models

name OR models

name models

Answer Source

for loops are looping through each index, so you then have to take that index and drill into the array

var myCollection = {
"cars": [
          { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
          { "name":"BMW", "models":[ "320", "X3", "X5" ] },
          { "name":"Fiat", "models":[ "500", "Panda" ] }
        ]
}
for ( x in myCollection.cars ) {
  let keys = Object.keys(myCollection.cars[x])
  document.getElementById("id1").innerHTML += keys[0] + "<br />";
}

the myCollection.cars[x] is how you get the specific object in the array and from the Object.keys() gives you the keys of that object. If you want the value and the key

for ( x in myCollection.cars ) {
  let keys = Object.keys(myCollection.cars[x])
  document.getElementById("id1").innerHTML += keys[0] + myCollection.cars[keys[0]] + "<br />";
}