MSDN Library

Object.keys Function (JavaScript)

Returns the names of the enumerable properties and methods of an object.





Required. The object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.

An array that contains the names of the enumerable properties and methods of the object.

If the value supplied for the object argument is not the name of an object, a TypeError exception is thrown.

The keys method returns only the names of enumerable properties and methods. To return the names of both enumerable and non-enumerable properties and methods, you can use Object.getOwnPropertyNames Function (JavaScript).

For information about the enumerable attribute of a property, see Object.defineProperty Function (JavaScript) and Object.getOwnPropertyDescriptor Function (JavaScript).

The following example creates an object that has three properties and a method. It then uses the keys method to obtain the properties and methods of the object.

// Create a constructor function that can be used
// to create an object.
function pasta(grain, width, shape) {
    // Define properties.
    this.grain = grain;
    this.width = width;
    this.shape = shape;

    // Define a method.
    this.toString = function () {
        return (this.grain + ", " + this.width + ", " + this.shape);

// Create an object.
var spaghetti = new pasta("wheat", 0.2, "circle");

// Put the enumerable properties and methods of the object in an array.
var arr = Object.keys(spaghetti);
document.write (arr);

// Output:
//   grain,width,shape,toString

The following example displays the names of all enumerable properties that start with the letter "c" in the window.document DOM object.

The keys method provides property names to the filter method, the filter method provides the names that start with "c" to the sort method, the sort method provides sorted names to the forEach method, and the forEach method displays the names.

var obj = window.document;


// Check whether the first character of a string is "c".
function CheckKey(value) {
    var firstChar = value.substr(0, 1);
    if (firstChar.toLowerCase() == "c")
        return true;
        return false;

function ShowKey(value) {
    document.write(value + "<br />");

Supported in the Internet Explorer 9 standards document mode. See Version Information.

Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards.

Community Additions

© 2016 Microsoft