Design & Download
Your JS Library
in Seconds!!!

Snippet: Get All Keys & Values

Written by Christopher West (cwest) on November 09, 2015.
One function to get all of the keys and another function to get all of the values in an array or an object.
function keys(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);
      }
    }
  }
  else {
    for (var k in arrOrObj) {
      if (opt_allKeys || has(arrOrObj, k)) {
        ret.push(k);
      }
    }
  }
  return ret;
}

function values(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(arrOrObj[k]);
      }
    }
  }
  else {
    for (var k in arrOrObj) {
      if (opt_allKeys || has(arrOrObj, k)) {
        ret.push(arrOrObj[k]);
      }
    }
  }
  return ret;
}

keys(arrOrObj [, opt_allKeys=false]) API Documentation

Description

Gets all of the keys in an array, arguments list or object.

Parameters

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

Returns

Returns an array of keys.

values(arrOrObj [, opt_allKeys=false]) API Documentation

Description

Gets all of the values in an array, arguments list or object.

Parameters

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

Returns

Returns an array of values.