SteveClason.com

 

JavaScript Articles

jQuery: .map()

The jQuery .map() Method

jQuery's .map() method provides for getting the elements of an array or object, then applying a function to each of those elements, returning the result as a new array or object. The method is described and many examples are given in the jQuery API.

The examples usually provided contain mathematical functions, covering very useful situations like (say) translating a table of product prices in US$ to another currency by grabbing the prices, calculating a new price in a selected currency, then displaying the results in a new table.

My example is slightly more ambitious, solving a less-common situation that arose for me, where a set of term/definition pairs were given in a dynamically-generated table which the client wanted translated to a html definition list (<dl>) for use in another part of their site.

Translating From a Table to a <dl>

The goal here it to manipulate the following table using jQuery, mapping the contents to a definition list and then printing that list to the document. This is an exercise of the jQuery .map() method, and to simplify things I didn't include the AJAXish stuff used to fetch the original table in the client project.

Term Definition
spam A delicious luncheon meat.
bologna A delicious, finely ground, luncheon meat.
liverwurst An awful, finely ground, luncheon meat.

Here's the code:

$(function() {
  var rows = $("tr").has("td"); // Only rows with body cells.
  var defs = new Array();
  $("#doit").click(function() {
    defs = $.map(rows, function(val) {
      console.log("val: " + val);
      // Get the first cell content, which is term.
      var term = $(val).children("td").first().text();
      var l = $("<dt>").text(term);
      // Get the second cell content, which is definition.
      var definition = $(val).children("td").last().text();
      var m = $("<dd>").text(definition);
      return $.merge(l, m);
    });
    
    console.log("defs: " + defs);
    $("dl").remove();
    $("<dl>").insertAfter("#test").addClass("lunchList");
    $(defs).each(function(idx, elt) {
      console.log("elt: " + elt);
      $(elt).appendTo("dl.lunchList");
    });
    
    $("dt").css("color", "green");
    $("dd").css("color", "red");
  });
});