SPavel SPavel - 3 months ago 23
Javascript Question

Why are these properties not enumerable?

I have a simple object of objects:

window.abilities = {
migrate:{
name:"Migrate",
description:"Move your tribe to another area; generate all new resources. Takes one time unit.",
image:"migrate.png",
action:"Migrate",
unlocked:true
},
eradicate:{
name:"Eradicate species",
description:"Remove a troublesome plant or animal",
image:"migrate.png",
action:"Eradicate",
unlocked:false
}
}


I am using a for ... in ... loop to iterate over this object and generate UI elements:

for(ability in window.abilities){
if(ability.unlocked){
$("#abilities").append(genAbilityCard(ability.name,ability.image,ability.description,ability.action));
}
}


However, each ability variable is empty - it only has the key and not the properties (name, description, and so forth). These properties seem to be unenumerable - even though properties created this way should be enumerable by default!

How can I make these properties enumerable implicitly, without using Object.defineProperty or something unwieldy like that?

Answer Source

Try iterating by using for..of and Object.values (ES6 only):

for (const ability of Object.values(window.abilities)){
    if (ability.unlocked){
        $("#abilities").append(genAbilityCard(ability.name,ability.image,ability.description,ability.action));
    }
}