Over a million developers have joined DZone.

Jquery Collect Function

·
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;
};
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}