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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

on that way array[0] will return object, not "id1", doesn't it?
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).
yes because jsfiddle.net/unkvs doesn't work, so i think it is not possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.