Design & Download
Your JS Library
in Seconds!!!

Snippet: entries() - Get All Key/Value Pairs

Written by Christopher West (cwest) on November 09, 2015.
Gets an array or arrays in which the sub-arrays are key/value pairs.
function entries(arrOrObj, opt_allKeys) {
  var ret = [];
  if (/^A(?:rguments|rray.*$)/.test(typeOf(arrOrObj))) {
    for (var k = 0, l = arrOrObj.length; k < l; k++) {
      if (opt_allKeys || has(arrOrObj, k)) {
        ret.push([k, arrOrObj[k]]);
      }
    }
  }
  else {
    for (var k in arrOrObj) {
      if (opt_allKeys || has(arrOrObj, k)) {
        ret.push([k, arrOrObj[k]]);
      }
    }
  }
  return ret;
}

This is a function which returns an array of the key/value pairs of an array, arguments list or an object.

API Documentation

Parameters

  1. arrOrObj {Array|Object}:
    The array, arguments list or object whose key/value pairs will be returned.
  2. opt_allKeys {boolean}:
    Optional. Defaults to false. If true then all key/value pairs will be returned. If false then only the key/value pairs where YourJS.has(key) is true will be returned.

Returns

Returns an array of key/value pairs. Each key/value pair will be an array where the first value is the key and the second is the value.