Design & Download
Your JS Library
in Seconds!!!

Snippet: map() - Map Array/Object Values

Written by Christopher West (cwest) on November 30, 2015.
Creates a new array or object with the same keys while getting the new values from the specified function.
function map(arrOrObj, fn, opt_mapAll) {
  fn = getSimpleCallback(fn);
  var ret = isArrayLike(arrOrObj) ? [] : {};
  walk(arrOrObj, function(v, k) {
    ret[k] = fn.apply(this, arguments);
  }, opt_mapAll);
  return ret;
}

map(...) API Documentation

Description

Creates a new array or object with the same keys while getting the new values from the specified function.

Parameters

  1. arrOrObj {Array|Object}:
    The array or object that is to be traversed.
  2. fn {function(value, key, arrOrObj)}:
    The callback to be called for each value in the array or object. The value returned will be stored as the property in the newly created array or object that is returned by YourJS.map().
  3. opt_mapAll {boolean}:
    Optional. Defaults to false. If true all array keys or object properties will be traversed even if they aren't owned by arrOrObj (which is determined by hasOwnProperty().

Returns

Returns the new array or object that contains the values returned from fn for each index/key that was traversed.