You can get an array of an object's own keys in JavaScript in the following ways:
- Using
Object.keys()
— returns only own enumerable keys (exceptSymbol
); - Using
Object.getOwnPropertyNames()
— returns all own keys (exceptSymbol
); - Using
Object.getOwnPropertySymbols()
— returns all ownSymbol
keys.
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).
Hope you found this post useful. It was published . Please show your love and support by sharing this post.