Design & Download
Your JS Library
in Seconds!!!

Snippet: walk() - Traverse Array/Object Values

Written by Christopher West (cwest) on November 09, 2015.
Traverses all of the properties of an object or all of the values of an array or array-like object. This is similar to the native forEach() function.
function walk(arrOrObj, fn, opt_walkAll) {
  var done, c = 0, k = 0, l, endWalk = function() { done = arguments; },
    caller = function(k) { c++; fn.call(endWalk, arrOrObj[k], k, arrOrObj); };
  if (isArrayLike(opt_walkAll)) {
    for (l = opt_walkAll.length; k < l; k++) {
      if (has(opt_walkAll, k)) {
        caller(opt_walkAll[k]);
        if (done) { break; }
      }
    }
  }
  else if (isArrayLike(arrOrObj)) {
    for (l = arrOrObj.length; k < l; k++) {
      if (opt_walkAll || has(arrOrObj, k)) {
        caller(k);
        if (done) { break; }
      }
    }
  }
  else {
    for (k in arrOrObj) {
      if (opt_walkAll || has(arrOrObj, k)) {
        caller(k);
        if (done) { break; }
      }
    }
  }
  return done && done.length ? done : c;
}

walk(...) API Documentation

Description

Traverses the specified array the same way that you would with a for loop or a for...in loop for an object.

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. If you want the current iteration to be the last iteration you can call this().
  3. opt_walkAll {boolean|Array}:
    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(). If this is an array, the values that will be traversed will be those found at the indices/names stored in the array.

Returns

If this(...) was called within fn(...), the arguments object of the arguments passed will be returned. Otherwise, returns the number of properties that were actually traversed.