Search code examples
javascriptjquerykeyassociative

jQuery Get associative array Key from index


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.


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.