GetOn GetOn - 6 months ago 11
jQuery Question

multidimensional name selector

So I've got a huge array like this:

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: 3},
{name: 'a cloth helmet' , item: 'helm' , value: 2}
]
}
},
'Cow' : {
info: {
'c_name' : 'Cow',
'HP' : '10',
'damage' : '1',
'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: 'a cloth helmet' , item: 'helm' , value: 2}
]
}
},
'dragon' : {
info: {
'c_name' : 'Cow',
'HP' : '300',
'damage' : '300',
'loot' : [
{name: 'an almighty dragon sword' , item: 'weapon' , value: 200},
{name: 'a dragon tooth', item: 'amulet' , value: 30},
{name: 'a pair of dragon boots' , item: 'boots' , value: 60},
{name: 'a dragon helmet' , item: 'helm' , value: 60}
]
}
},

}

},
},
'level2' : {
'skelleton' : {
'HP' : '40',
'damage' : '5',
'loot' : [
{name: 'a bone' , item: 'weapon' , value: 1},
{name: 'a warriors helmet' , item: 'helm' , value: 4}
]
}
}

};


and when I select the creature I want I need to call it like this:

enemy.level1.creature.creature_name.dragon.info.c_name


Now I want to be able to choose an enemy by a
input box
or something like that.
But I can't figure out how I insert that value in the
enemy.level1.creature.creature_name.dragon.info.c_name


I tried using
enemy.level1.creature.creature_name.+ input_value + .info.c_name


But that doesn't seem to work. Must be a simple solution for this?

Answer

What you have is an object not an array. You can set object properties in multiple ways. One way would be like:

var myObj = {
  foo: {
    value : "foo"
  },
  bar: {
    value: "bar"
  }
}

myObj["foo"] = "123";

In your case you object is bigger but the process is the same:

enemy.level1.creature.creature_name[input_value].info.c_name = "whatever name";

where input value is one of the valid properties of creature_name, ie "dragon":

enemy.level1.creature.creature_name["dragon"].info.c_name = "whatever name"