JavaScript – How to get an array of object keys

The goal

Given a Javascript object you want to get an array of its keys. For example, given the following object:

var myObj = {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "+1 234 567 890",
    emailAddress: "john.doe@example.com"
}

You want to get its keys into an array:

["firstName", "lastName", "phoneNumber", "emailAddress"]

The problem

This can easily be achieved using Object.keys() like this:

var myObj = {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "+1 234 567 890",
    emailAddress: "john.doe@example.com"
};

var myKeys = Object.keys(myObj);
console.log(myKeys);

The code above works great in Chrome:

But throws an ‘Object doesn’t support property or method keys’ error in IE 8 or earlier:

A solution

This is a possible solution which works in both browsers:

var myObj = {
    firstName: "John",
    lastName: "Doe",
    phoneNumber: "+1 234 567 890",
    emailAddress: "john.doe@example.com"
};

var objectKeys = Object.keys || function(obj) {
    var res = [];
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
    }
    return res;
};

myKeys = objectKeys(myObj);
console.log(myKeys);

Seems to work okay in IE 8 and earlier:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.