DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Jquery Collect Function

05.27.2010
| 5995 views |
  • submit to reddit
        A jquery $.collect() function, analogous  to Ruby's collect. jQuery has a $.map() function already, but it isn't ideal.

Example of how $.map() works:

given an array
var a = ["a", "b", "c"]
and a function to operate on members of the array
function k_v(key, value) {
 return { k: key, v : value }
}
$.map() returns an array of objects, except that the keys and values are mixed up because the arguments order of $.map() is
opposite the argument order of $.each !!
var results = $.map(a, k_v) 
results = [{ k : "a", v : 0}, {k : "b", v: 1}, {k : "c", v : 2}]

let's try an object instead
var o = {0 :"a", 1:"b", 2:"c"}
results = $.map(o, k_v)

returns an empty array !!
results = []

now let's use $.collect()
results = $.collect(a, k_v)

results = [{ k : "0", v : "a" }, { k : "1", v : "b"}, { k : "2", v : "c" } ]
results = $.collect(o, k_v)
results = [{ k : 0, v : "a" }, { k : 1, v : "b"}, { k : 2, v : "c" } ]

Here's the $.collect() code.
$.collect = function(c, f) {
  var a = [];
  $.each(c, function(k, v) {
    a.push(f(k, v));
  });
  return a;
};