jQuery: using associative arrays

JavaScript has no native notion of associative arrays. Unlike PHP, JavaScript uses object literals to mimic the basic behavior of associative arrays. For example:

var arr = {};

arr['foo'] = 'bar';

alert(arr.foo); // alerts 'bar'

We can also create this kind of arrays in a dynamic way, like so:

var arr = {};
var items = ['foo,bar', 'boo,baz'];

for(var i=0; i<items.length; i++) {

   var item = items[i];
   var values = item.split(',');
   arr[values[0]] = values[1];



jQuery uses this kind of array-like objects for some of its Ajax methods (such as $.post()). We can actually retrieve the names and values of form elements and turn them in an associative array. Example:

var values = {};

$('#form :input').not(':submit').each(function() {

    var $input = $(this);
    var name = $input.attr('name');
    var value = $input.val();
    values[name] = value;

Now we can use $.post():

$.post('process.php', values, function(response, content){

    // do something here


As you can see, retrieving this kind of values is pretty straightforward.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.