简体   繁体   中英

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 />";
}


Likewise how can I display the value which is inside the array ie or 值,

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


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


       
OR

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 ) {
  var 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 ) {
  var keys = Object.keys(myCollection.cars[x])
  document.getElementById("id1").innerHTML += 
     keys[0] + " : " + myCollection.cars[x].name + " <br />" +
     keys[1] + " : " + myCollection.cars[x].models + "<hr />";
}

This for in is mean't for object's. You are using an array so its returning index. Instead use a forEach like shown below.

 var myCollection = { "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ] } myCollection.cars.forEach(function (value) { //console.log("name" + value.name + ", models" + value.models); //for printing cars alonecars console.log(value.name); //for print models alone value.models.forEach(function (model) { console.log(model); }); }); 

The line below comments will get your desired output, you can print either cars or models.

Here you go with a solution https://jsfiddle.net/sg6kj0n7/1/

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM