How to Get an Array of JavaScript Object's Own Keys?

You can get an array of an object's own keys in JavaScript in the following ways:

Using Object.keys()

The Object.keys() method returns an array of object's own enumerable property names (excluding Symbol properties):

// ES5+
const sym1 = Symbol('a');
const sym2 = Symbol('b');

const obj = Object.create({}, {
    foo: { value: 'bar', enumerable: true },
    baz: { value: 'qux', enumerable: false },
    [sym1]: { value: 'quux', enumerable: true },
    [sym2]: { value: 'quuz', enumerable: false },
});

const keys = Object.keys(obj);

console.log(keys); // [ 'foo' ]

Using Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() method returns an array of all object's own string property names (including non-enumerable properties, and excluding Symbol properties):

// ES5+
const sym1 = Symbol('a');
const sym2 = Symbol('b');

const obj = Object.create({}, {
    foo: { value: 'bar', enumerable: true },
    baz: { value: 'qux', enumerable: false },
    [sym1]: { value: 'quux', enumerable: true },
    [sym2]: { value: 'quuz', enumerable: false },
});

const keys = Object.getOwnPropertyNames(obj);

console.log(keys); // [ 'foo', 'baz' ]

Using Object.getOwnPropertySymbols()

The Object.getOwnPropertySymbols() method returns an array of object's own Symbol properties (excluding all other string properties):

// ES6+
const sym1 = Symbol('a');
const sym2 = Symbol('b');

const obj = Object.create({}, {
    foo: { value: 'bar', enumerable: true },
    baz: { value: 'qux', enumerable: false },
    [sym1]: { value: 'quux', enumerable: true },
    [sym2]: { value: 'quuz', enumerable: false },
});

const keys = Object.getOwnPropertySymbols(obj);

console.log(keys); // [Symbol(a), Symbol(b)]

Please note that all objects have no own Symbol properties initially, therefore, Object.getOwnPropertySymbols() returns an empty array (unless you explicitly set Symbol properties on an object).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.