jQuery.map()S2C Home « Utilities « jQuery.map()

Map to an array.

Description

The jQuery.map() jQuery General utility method, returns a JavaScript Array object translated from an array or object.

Shorthand version $.map()

  • Prior to version 1.6 of jQuery, the jQuery.map() jQuery General utility method will only work on Array objects.
  • In versions of jQuery prior to 1.6, array-like objects (objects containing a length property with a value), can be converted to arrays using the jQuery.makeArray() jQuery General utility method, before using this method.

Syntax

Signature Description
jQuery.map(arrayOrObject, callback(value,indexOrKey))Return a JavaScript Array object translated from an array or object.

Parameters

Parameter Description Type
arrayOrObjectThe Array or Object to translate.Array or
Object
callback(value, indexOrKey)A function to process on each item / property of the collection.
value - The current array index value of the item / the object key.
indexOrKey - The array item value / object key value.
  • The callback is fired in the context of the arrayOrObject we are iterating over, and the keyword this refers to the global window object.
  • The function can return:
    • the translated value, which will be mapped to the resulting array.
    • null or undefined, to remove the item.
    • An array of values that gets flattened into the full array.
Function

Return

An Array object.

jQuery.map( arrayOrObject,
            callback( value,indexOrKey ) )
ExampleTop

Return a JavaScript Array object translated from an array or object.

In the example below when we press the button the first time we create an an object and then flatten it to an array using the jQuery.map() jQuery General utility method. An interesting thing to note is how we lose the original skills key in the flattening. You can use the jQuery.extend() method for these situations.



$(function(){
  $('#btn19').one('click', function(){
    var obj1 = {species: 'penguin', skills: {flight: 'no', swim: 'yes'}, climate: 'cold'};
    arr0 = $.map( obj1, function(val, i) { return val };
    $('#div15').append('Our new array holds the values: '  + JSON.stringify(arr0));
  });
});

div15. Some initial text.

Press the button below to action the above code: