hippietrail
hippietrail

Reputation: 16974

Does jQuery have something like .map() which returns an object rather than an array?

jQuery has the .map() function which takes as input either an array or an object but can only output an array.

It seems there are plenty of times when you want to output something more like an associative array so is there another function in jQuery that can output a JavaScript Object?

(I'm pretty sure I've used something like this in another programming language, possibly Perl.)

Upvotes: 3

Views: 619

Answers (1)

Patches
Patches

Reputation: 1125

You can get the same result by declaring the object first, then building it out in the .map() function instead of returning the data.

This example gets all the checkboxes on the page and creates an object out of their ids and values:

var result = new Object();
$(':checkbox').map(function() {
    result[this.id] = this.value; 
});

Upvotes: 3

Related Questions