-1

I have an array in javascript and I want to use its values as keys for another array.

var arrKeys = ['place', 'name', 'age' ];
var result = [place]['name']['age'] = 5;

Now I want to check if there is a value for this keys in another associative array:

if ( result[place][name][age] {
   console.log('exists');
}

How can I use the values from arrayKeys as array keys in the result array?

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • `result[arrKeys[0]][arrKeys[1]][arrKeys[2]]` maybe? – Ja͢ck Mar 25 '14 at 08:59
  • Use objects instead of arrays. http://stackoverflow.com/questions/8067590/associative-array-versus-object-in-javascript – Pramod Mar 25 '14 at 08:59
  • 1
    Hey Ronny, there is so much wrong with this code. var result = ~~~ = ~~~~. That is never a way to go in JS – Nicky Smits Mar 25 '14 at 09:07
  • @Nicky **do not change code**, especially in questions. Post new answer if you want that explain "here is your typo" and how to fix it. – Shadow The GPT Wizard Mar 25 '14 at 09:15
  • Aha. ok, fair enough. in this part (var result = [place]['name']['age'] = 5;). You have three indexes: place,'name','age'. The first one is a variable, the second and third are constant. This can not be the intention, and if it is, you have to provide more code. – Nicky Smits Mar 25 '14 at 09:20

2 Answers2

0

Really easy:

var result = new Array();

var arrKeys = ['place', 'name', 'age' ];
result[arrKeys['place']][arrKeys['name']][arrKeys['age']] = 5;

However. This might still give you some errors. So i would do it like this, just to be save.

var arrKeys = ['place', 'name', 'age' ];
var result = new Array();
result[arrKeys['place']] = new Array();
result[arrKeys['place']][arrKeys['name']] = new Array();
result[arrKeys['place']][arrKeys['name']][arrKeys['age']] = 5;

As you can probably see, this is the way to set the variable you want. You can acces the variable again with:

result[arrKeys['place']][arrKeys['name']][arrKeys['age']]
Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
0

Something like:

for (i=0;i<arrKeys.length;i++) {
  if (typeof(result[arrKeys[i]])!="undefined") {
    console.log('exists');
  }
}

Could this work for you?

dkasipovic
  • 5,930
  • 1
  • 19
  • 25