Object.keys()


Object.keys() (ES5+): Array of property names.

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a for...in loop would. This is incredibly useful for iterating over the properties of an object or for converting an object's keys into an array for further manipulation. Remember for in loop is crucial and may want to review it as we cover this section. 


Example 1: Basic Usage

// Define a simple object representing a user.
const user = {
  name: 'Jane Doe',
  email: 'jane.doe@example.com',
  age: 28
};

// Retrieve the keys of the user object.
const userKeys = Object.keys(user);

// Log the array of keys to the console.
console.log(userKeys); // Output: ['name', 'email', 'age']

Explanation: This example demonstrates the fundamental use of Object.keys(). It takes the user object and returns an array containing the names of its properties: "name", "email", and "age".


Example 2: Checking for an Empty Object

// An object with no properties.
const emptyObject = {};

// An object with properties.
const nonEmptyObject = { item: 'sample' };

// Check the length of the keys array to determine if the object is empty.
const isObjectEmpty = Object.keys(emptyObject).length === 0;

// Log the result.
console.log(isObjectEmpty); // Output: true

Explanation: A common use case for Object.keys() is to check if an object is empty. If the length of the array returned by Object.keys() is zero, it confirms that the object has no enumerable properties.


Example 3: Iterating Over Object Properties

// An object representing product inventory.
const inventory = {
  apples: 150,
  oranges: 80,
  bananas: 200
};

// Use Object.keys() with forEach to iterate over the properties.
Object.keys(inventory).forEach(key => {
  console.log(`Item: ${key}, Quantity: ${inventory[key]}`);
});

Explanation: This code snippet shows how to loop through an object's properties. Object.keys() provides the property names, which are then used with a forEach loop to access the corresponding values within the inventory object.


Example 4: Filtering Object Properties

// An object with mixed data types.
const data = {
  id: 1,
  name: 'product',
  value: 120,
  isActive: true,
  description: 'A sample product'
};

// Filter keys that start with the letter 'i'.
const filteredKeys = Object.keys(data).filter(key => key.startsWith('i'));

// Log the filtered keys.
console.log(filteredKeys); // Output: ['id', 'isActive']

Explanation: Here, Object.keys() is combined with the filter() array method to create a new array containing only the keys from the data object that meet a specific condition, in this case, starting with the letter 'i'.


Example 5: Dynamic Property Access

// A configuration object.
const config = {
  host: 'localhost',
  port: 8080,
  protocol: 'http'
};

// Dynamically build a connection string.
let connectionString = '';
Object.keys(config).forEach((key, index) => {
  connectionString += `${key}=${config[key]}`;
  if (index < Object.keys(config).length - 1) {
    connectionString += '&';
  }
});

console.log(connectionString); // Output: host=localhost&port=8080&protocol=http

Explanation: This example demonstrates dynamically accessing and utilizing both the keys and values of an object. Object.keys() is used to iterate through the config object and build a query-like string.


Example 6: Non-Enumerable Properties

// An object with a non-enumerable property.
const myObject = {};
Object.defineProperty(myObject, 'nonEnumerableProp', {
  value: 'hidden',
  enumerable: false
});
myObject.enumerableProp = 'visible';

// Get the enumerable keys.
const keys = Object.keys(myObject);

// Log the keys.
console.log(keys); // Output: ['enumerableProp']

Explanation: Object.keys() only returns enumerable properties. This example defines one enumerable and one non-enumerable property to illustrate that nonEnumerableProp is not included in the resulting array.


Example 7: Objects with Number Keys

// An object with keys that are numbers.
const numericKeys = {
  '2': 'two',
  '1': 'one',
  '3': 'three'
};

// Get the keys.
const sortedKeys = Object.keys(numericKeys);

// Log the keys. Note that they are sorted numerically.
console.log(sortedKeys); // Output: ['1', '2', '3']

Explanation: When an object's keys can be parsed as integers, Object.keys() returns them in ascending numerical order, regardless of their original order in the object definition. This is a specific behavior for integer-like keys.