keys

Introduced in JavaScript 1.8.5

Summary

Returns an array of all own enumerable properties found upon a given object, in the same order as that provided by a for-in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Method of Object
Implemented in JavaScript 1.8.5
ECMAScript Edition ECMAScript 5th Edition

Syntax

Object.keys(obj)

Parameters

obj
The object whose enumerable own properties are to be returned.

Description

Object.keys returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

Examples

var arr = ["a", "b", "c"]; alert(Object.keys(arr)); // will alert "0,1,2"

// array like object
var obj = { 0 : "a", 1 : "b", 2 : "c"};
alert(Object.keys(obj)); // will alert "0,1,2"

// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
my_obj.foo = 1;

alert(Object.keys(my_obj)); // will alert only foo

If you want all properties, even the not enumerable, see Object.getOwnPropertyNames

Compatiblity

To add compatible Object.keys support in older environments that do not natively support it, copy the following snippet:

if(!Object.keys) Object.keys = function(o){
 if (o !== Object(o))
      throw new TypeError('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;
}

Browser support

Based on Kangax's compat table.

  • Desktop
  • Mobile

Feature Firefox (Gecko) Chrome Internet Explorer Opera Safari
Basic support 4 (2.0) 5 9 -- 5
Feature Firefox Mobile (Gecko) Android IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

Tags (3)

Attachments (0)

 

Attach file