How to find keys of a hash

javascript – How to find keys of a hash?

There is function in modern javascript (ECMAScript 5) called Object.keys performing this operation:

var obj ={"a":1,"b":2,"c":3};
alert(Object.keys(obj));// will output ["a", "b", "c"]
Object.prototype.keys =function(){
  var keys =[];
  for(var i inthis)if(this.hasOwnProperty(i))
  {
    keys.push(i);
  }
  return keys;}
if(!Object.keys)Object.keys =function(o){
   if(o !==Object(o))
      thrownewTypeError('Object.keys called on non-object');
   var ret=[],p;
   for(p in o)if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
   return ret;}

On Mozilla site there is also a snipped for backward compatibility:

 

 

 

 

 

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s