Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 363
hippietrail Avatar asked Jun 08 '26 04:06

hippietrail


1 Answers

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; 
});
like image 190
Patches Avatar answered Jun 10 '26 18:06

Patches



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!