简体   繁体   中英

How do I get the correct object variable names in the grandCouncil array?

When I console.log(grandCouncil) I end up getting this:

[Object, Object, Object]

What I want to see is the names of the variables instead likes this:

[jungleAnimal1, jungleAnimal2, jungleAnimal3]

Here is my code:

var grandCouncil = [];


var jungleAnimal1 = {
  'type': "frog",
  'collects': ['flys','moths','beetles'],
  'canFly': false
};

var jungleAnimal2 = {
  'type': "jaguar",
  'collects': ['wild pigs','deer','sloths'],
  'canFly': false
};

var jungleAnimal3 = {
  'type': "parrot",
  'collects': ['fruits','bugs','seeds'],
  'canFly': true
};

grandCouncil.push(jungleAnimal1,jungleAnimal2,jungleAnimal3);
console.log(grandCouncil);

jungleAnimal1,2 and 3 are object literals.

When you push them into the grandCouncil array, references to those objects are added to the array, but the variable names are not.

If you want to use jungleAnimal1,2 and 3 as properties under grandCouncil, grandCouncil should be an object and the animals can be properties, like so:

grandCouncil = {
    "jungleAnimal1" : { // type, collects, canFly }
    "jungleAnimal2" : ...
    "jungleAnimal3" : ...
}

Thank you @zerkms for the clarification

The values stored in the array are Objects; for example, you can access the values of the object by using dot notation, so to access jungleAnimal2's type would simply be:

grandCouncil[1].type

You could

for(var i = 0;i < grandCouncil.length; i++){
    for(animal in grandCouncil[i]){
        console.log(animal);   
    }
}

This is simply iterating over each array element, which is an object, and then iterating through each element in those objects. You can access specific properties by using the aforementioned dot notation, so to console.log all types, just do animal.type .

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