views:

109

answers:

6
arr[key] = value;

where key is a jQuery object and value is an array.

+5  A: 

Associative arrays don't really exist in JavaScript. However, you can achieve similar functionality using JavaScript objects:

// Create object
var myObject = {
    key: value,
    helloText: "Hello World!"
};

// Access object in some statement via:
myObject.helloText
// ...or:
myObject["helloText"]

To use an object as a key, you would have to do something like:

var a = {
    helloText: "Hello World!"
};

var b = {};
b[a] = "Testing";

alert(b[a]); // Returns "Testing" (at least, in Safari 4.0.4)

Using an object as a key sounds a bit weird, though. Are you sure you need to do this?

Update:

You can't actually use an object as a key in JavaScript. The reason the above code appears to work is that, in the statement b[a] = "Testing";, JavaScript converts a to a string via a.toString(), which results in "[object Object]", and uses this string as the key. So our statement is actually b["[object Object]"] = "Testing"; and our alert statement is exactly the same as alert(b["[object Object]"]);.

Thanks to CMS for pointing this out in the comments!

Update 2:

Tim Down points out that his JavaScript library jshashtable allows you use an object as a key.

Steve Harrison
Why is works?Very strange
The second example *seems* to work because the property accessor (*the bracket notation*) internally converts the property expression (*what is between the brackets*) to `String`, in that example `b` ends with a property named `"[object Object]"`. That is the result of the `toString` operation applied to `a`, because of that you can't really add more objects (they will just change that property value). Try `alert(b["[object Object]"]);` and it will show `"Testing"` also.
CMS
Using arbitrary objects as key is exactly the point of hashmaps and associative arrays. However, using a jQuery object as key, even if it were possible (which it isn't), sounds like a bad idea, because jQuery objects can change. A key needs to be constant, like the id of the DOM object. And that's a string, so you can use that as a key. Maybe using the jquery selector is an option, but that can contain characters that probably won't be acceptable for javascript properties (like #, . and spaces).
mcv
@CMS: Ah, that makes sense! I've updated my answer accordingly. Thanks!
Steve Harrison
You're welcome @Steve!, more info about the property accessors here: http://bclary.com/2004/11/07/#a-11.2.1
CMS
+1  A: 

You can't use objects as keys, and assocative arrays are not what they seem in Javascript because all you're doing is setting a property on the array object, when you loop through by the .length it natively doesn't account for the manually defined properties you set.

I suggest storing the elements and arrays inside of object literals, all inside of an array. Eg:

var list = [
    {
        el:document.body,
        arr:[1,2]
    }
];

for ( var i = 0, l = list.length; i<l; ++i ) {
    alert( list[i]['el'] )
    alert( list[i]['arr'][0] )
}

// add elements to the array

list.push({
    el:document.body.firstChild,
    arr:[3,4]
})

As kprime mentioned in his answer though, it might be better to use .data() if you are using Javascript.

if ( !$(el).data('key') ) {
    $(el).data('key', [2,3,4] );
}
meder
+1  A: 

Just guessing here, but it seems you're trying to associate some (arbitrary) data with a jQuery object (possibly an element). In that case, why not use the data () method?

$('#el').data (value);
K Prime
i would recommend this as well, forgot he mentioned jQuery.
meder
Well, in the first version of the question, `key` was said to be a DOM element, and the question wasn't jquery tagged, as far as I remember. That's what got us on the "wrong"/more cumbersome track.
Tom Bartel
A: 

I would suggest assigning a unique ID to each element you want to put in the associative container (object in JS) and use the ID as key:

var idCounter = 0;
var container = { };
function storeValue(element, value) {
    if (!element.getAttribute('id')) {
        element.setAttribute('id', makeID());
    }
    var id = element.getAttribute('id');
    container[id] = value;
}
function makeID() {
    return 'unique-id-' + idCounter++;
}

EDIT: This solution assumes that jQuery is not available. If it is, use data('key', value).

Tom Bartel
+2  A: 

You can use jshashtable, which allows any JavaScript object as a key.

Tim Down
Very interesting! Thanks for the link.
mcv
A: 

every javascript object is an associative array, this is a property build in the language, you do not need to anything special, just use it like that

test2
See the comments to the first answer posted.
Tim Down