GetOn GetOn - 6 months ago 10
jQuery Question

Loop through object array

I've got this array

var enemy = {
'level1' : {
creature :
{
creature_name : {
'Goblin' : {
info: {
'c_name' : 'Goblin',
'HP' : '20',
'damage' : '3',
'loot' : [
{name: 'a wooden sword' , item: 'weapon' , value: 2},
{name: 'a golden necklace', item: 'amulet' , value: 1},
{name: 'a pair of boots' , item: 'boots' , value: 1},
{name: 'some cloth legs' , item: 'legs' , value: 1},
{name: 'a cloth helmet' , item: 'helm' , value: 1}
]
}
},
'Cow' : {
info: {
'c_name' : 'Cow',
'HP' : '10',
'damage' : '1',
'loot' : [
{name: 'bell' , item: 'weapon' , value: 0},
{name: 'cow hide cloak' , item: 'cape' , value: 1},
{name: 'a wooden sword' , item: 'weapon' , value: 2},
{name: 'a golden necklace' , item: 'amulet' , value: 1},
]
}
},
'Dragon' : {
info: {
'c_name' : 'Dragon',
'HP' : '100',
'damage' : '5',
'loot' : [
{name: 'an almighty dragon sword' , item: 'weapon' , value: 5},
{name: 'a dragon tooth', item: 'amulet' , value: 5},
{name: 'a pair of dragon boots' , item: 'boots' , value: 4},
{name: 'a dragon helmet' , item: 'helm' , value: 4}
]
}
},

}

},
},


I want to receive the _creature_name_ I looked on other topics and saw foreach loops with arrayname.length but when I try to do
enemy.length
or
enemy.level1.creature.creature_name.length
I get undefined. I have no clue how to receive all the creature names

Answer
$('#enemy_list')[0].innerHTML = 'Enemies: <br />Level 1: <br />';
for(var enemy_names in enemy['level1'].creature.creature_name){
    $('#enemy_list')[0].innerHTML += enemy_names + '<br />';
}

You need create a prop for the name inenemy['level1'].creature.creature_name and then foreach enemy_name place it in the containing div. Goodluck!

By the way, your problem with the for loop was that you executed the enemies: <br /> level1: <br /> in your for loop aswell so it would display it 3 times. This method you put the names inside the div containing the text only once.