Question

My question is the following, in an array:

    var array = new Array();
    array['abc'] = 'value1';
    array['def'] = 'value2';

How do I get the associative key of an array if I have its index number? Let's say I want associative key of arr[0]'s associative key ( => 'abc'), or associative key of arr[1] '=> 'def'). How is this possible in jQuery?

Let's be clear, I am not looking for the value and I do not need to use $.each(). I just need to link 0 to 'abc' and 1 => 'def' etc... Unfortunately something like arr[0].assoc_key() doesn't seem to exist T_T Thanks a bunch.

Was it helpful?

Solution

All right so the solution is pretty simple, you need to create an object which associates indeces with keys as well as keys with values. Here is a JSBin that works. Please note that to add an element, you need a custom function (addElement in this case) to be able to have both indeces and keys associated at the right places. This is a rough draft to give you an idea of how it can be done!

JSBin

If you have any question or if that wasn't exactly what you expected, simply edit your question and I'll have another glance at it. It HAS to be a custom made object if you want the behavior you asked for.

OTHER TIPS

Javascript doesn't have a native Dictionary type, you would have to write it. – T McKeown

It isn't possible and jQuery doesn't come into the picture at all. If you use an array as a dictionary like that, you are doing something wrong. – Jon

rethink the way you are doing it. Maybe try array[0] = {key: 'abc', value: 'value1'} – Geezer68

@Geezer68, objects do not support multidimentional data, the array I'm working on is 3 levels deep (I know I didn't says so in my original post, but I didn't think it was relevant).

Anyway, thank you guys, it answers the question! I will rethink it then ;-)

EDIT: I guess I'll just add a level:

    var array = new Array();
    array[] = 'abc';
    array[0] = 'value1'

I don't know an other than using a for ... in. So here how i do it and hope you get a better answer (because i want to know aswell!).

var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';

var listKeys = [];
for(x in array) listKeys.push(x);

console.log(listKeys); // ['abc', 'def']

but using [string] on an array object is adding property to the object, not the array. So it may be better to initialise it like that :

var array = {};

You might learn more information on this technique in this question and some restriction on why you should not rely on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top