๐ The Object.keys()
method returns an array of a given object's own enumerable property names, or in simple words, the array of all the keys of an object.
๐ Syntax
Object.keys(object)
๐ Here are some of the major points you have to remember while using Object.keys()
The ordering of the properties is the same as that given by looping over the properties of the object manually.
In ES5, if the argument to this method is not an object (a primitive), then it will cause a TypeError.
From ES2015 onwards, a non-object argument will be coerced to an object.
If the properties have any numbered names, Object.keys will sort them.
๐ Examples:
/** Simple usage */
const user = {
username: 'rehan-sattar',
age: 22,
isActive: true
};
console.log(Object.keys(user));
// expected output: ["username", "age", "isActive"]
--------------------------------------------------------
/** Type Coercion */
// In ES5
Object.keys('foo'); // TypeError: "foo" is not an object
// In ES2015+
Object.keys('foo'); // ["0", "1", "2"]
--------------------------------------------------------
/** Sorting keys example */
const obj = { "greet": "Hi!", "1": "Byee", "0": "Oh!" };
Object.keys(obj);
// expected output: ["0", "1", "greet"]
๐ References:
The official MDN documentation of Object.keys()
๐ Follow me:
ย