0

I want to create a nested array in Javascript but can't do the thing what I want, I don't know if it is even possible. Here is an example of what kind of array I want to create:

var array = ['id1', 'id2', 'id3', 'id4'];

Then I want to add new array for each id such way that id values stayed the same. Why? because I want to use indexOf method to find out the element index of main array with sub array id. Something like this:

array[0]['par1'] should return the value of parameter1
array[0]['par2'] should return the value of parameter2

...

array[0] should return "id1" because

alert(array.indexOf("id1"))   must return 0 ;

If there is some way of doing it, that would be great to know, but if it is not than I think I will use 2 arrays, one will hold sub arrays and another the ids

sorry for my bad English, I tried my best to explain my needs.

Irakli
  • 1,151
  • 5
  • 30
  • 55

1 Answers1

2

Maybe you want to do

array[0] = {par1: 'somevalue', par2: someother};
array[1] = {par1: 'anotehrone', par2: stillanother};

This sets as elements of you array javascript objects, here used as associative arrays. They enable you to set or get elements by key :

array[0]['par1'] = 'new value'; // write
var newval = array[0]['par1']; // read

But if you also want to have array[0] returning something that's not a generic object but a string... then you probably don't want javascript. This language just doesn't work like that.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • on that way array[0] will return object, not "id1", doesn't it? – Irakli Sep 11 '12 at 16:59
  • 1
    Yes. I now think after rereading your question I should have answered (as comment) that it's not possible to fulfill all your requirements without bad hacks. You probably should use objects (maybe classes). – Denys Séguret Sep 11 '12 at 17:04
  • yes because http://jsfiddle.net/unkvs/ doesn't work, so i think it is not possible – Irakli Sep 11 '12 at 17:06