One common thing that I end up doing, for work and person projects, when writing JavaScript is iterating over all of the properties of an object that I create. Since this task is quite common, I often wrote a each or forEach function for each project. In my most recent project though I decided that it would be cool to not only publish the function so that I and others can easily find and use it but also to add in the option of returning the property names. Here is the function that I came up with:


/**
 * @license Copyright 2013 - Chris West - MIT Licensed
 */
(function(hasOwnProperty) {
  /**
   * Iterates over all of the properties of the specified object and returns an
   * array of their names.
   * @param {!Object} obj  The object whose properties will be iterated over.
   * @param {function(string, *, !Object):*=} fnCallback  Optional function
   *     callback which, if specified, will be called for each property found.
   *     The parameters passed will be the name of the property, the value of
   *     the property and the object.
   * @return {!Array.<string>}  Returns an array of the names of the properties
   *     found.  If the fnCallback was specified, the only property names that
   *     will be returned will be those for which the fnCallback function
   *     returned a true-ish value.
   */
  eachProperty = function(obj, fnCallback) {
    var ret = [];
    for(var name in obj) {
      if(hasOwnProperty.call(obj, name) && (!fnCallback || fnCallback(name, obj[name], obj))) {
        ret.push(name);
      }
    }
    return ret;
  };
})(({}).hasOwnProperty);

Example

Here is an example of how the above function could be used:


var person = {
  name: 'Chris West',
  gender: 'male',
  age: 25
};

var personProperties = eachProperty(person);
alert('This person has the following properties:  '
  + personProperties.join(', '));
eachProperty(person, function(name, value) {
  alert('My ' + name + ' is ' + value + '.');
});

The following messages will be printed from the above example, each in a separate alert box:

  1. This person has the following properties: name, gender, age
  2. My name is Chris West.
  3. My gender is male.
  4. My age is 25.

It is important to note that depending on the JavaScript engine, the ordering of the property names may vary within the returned array and when the callback is called.

Description

This function iterates over all of the properties of the specified object. This function can both act like the Object.keys and an iterator function of all properties specifically defined for the given object (not prototype defined values).

Parameters

  1. obj {Object}:
    The object whose properties will be iterated over.
  2. fnCallback {Function}:
    Optional function which, if specified will be called for each property found. The parameters passed will be the name of the property, the value of the property and the object.

Returns

Returns an array of the names of the properties found. If the fnCallback was specified, the only property names that will be returned will be those for which the fnCallback function returned a true-ish value.

Final Notes

In summary, this eachProperty function can prove to be very useful. In fact, as I always say with all useful functions, if and when the next version jPaq comes out, I will make sure that this function is included. Until then, please feel free to use this code in your own projects. šŸ˜‰


Leave a Reply

Your email address will not be published. Required fields are marked *