[javascript] How to find keys of a hash?

I know in javascript Objects double as hashes but i have been unable to find a built in function to get the keys

var h = {a:'b',c:'d'};

I want something like

var k = h.keys() ; // k = ['a','c'];

It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?

I keep feeling it must be a simple built in function that I missed but I can't find it!

This question is related to javascript object key

The answer is


This is the best you can do, as far as I know...

var keys = [];
for (var k in h)keys.push(k);

using jQuery you can get the keys like this:

var bobject =  {primary:"red",bg:"maroon",hilite:"green"};
var keys = [];
$.each(bobject, function(key,val){ keys.push(key); });
console.log(keys); // ["primary", "bg", "hilite"]

Or:

var bobject =  {primary:"red",bg:"maroon",hilite:"green"};
$.map(bobject, function(v,k){return k;});

thanks to @pimlottc


I wanted to use the top rated answer above

Object.prototype.keys = function () ...

However when using in conjunction with the google maps API v3, google maps is non-functional.

for (var key in h) ...

works well.


For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure Object.keys in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty feature.

As of ECMAScript 5 - Object.defineProperty

As of ECMA5 you can use Object.defineProperty() to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    var keys = [];
    for(var i in this) if (this.hasOwnProperty(i)) {
      keys.push(i);
    }
    return keys;
  },
  enumerable: false
});

var o = {
    'a': 1,
    'b': 2
}

for (var k in o) {
    console.log(k, o[k])
}

console.log(o.keys())

# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]

However, since ECMA5 already added Object.keys you might as well use:

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    return Object.keys(this);
  },
  enumerable: false
});

Original answer

Object.prototype.keys = function ()
{
  var keys = [];
  for(var i in this) if (this.hasOwnProperty(i))
  {
    keys.push(i);
  }
  return keys;
}

Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.

There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.


you can use Object.keys

Object.keys(h)

if you are trying to get the elements only but not the functions then this code can help you

this.getKeys = function() {

var keys = new Array();
for(var key in this) {

    if( typeof this[key] !== 'function') {

        keys.push(key);
    }
}
return keys;

}

this is part of my implementation of the HashMap and I only want the keys, this is the hashmap object that contains the keys


You could use Underscore.js, which is a Javascript utility library.

_.keys({one : 1, two : 2, three : 3}); 
// => ["one", "two", "three"]

I believe you can loop through the properties of the object using for/in, so you could do something like this:

function getKeys(h) {
  Array keys = new Array();
  for (var key in h)
    keys.push(key);
  return keys;
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?