Lodash _.keys: Returned Array of Strings Explained

The _.keys method in the Lodash library retrieves the property names of a given object and returns them as an array of strings. This guide explains precisely what values are included in this array, how different data types are handled, and how _.keys differs from related methods like _.keysIn and native JavaScript alternatives.

What Does _.keys Return?

The _.keys(object) method returns an array of strings representing the own enumerable property names of the specified object.

Three specific conditions define which keys appear in the resulting array:

  1. Own Properties Only: The method inspects only properties directly assigned to the target object. It ignores inherited properties from the object's prototype chain.
  2. Enumerable Properties Only: Properties created with enumerable: false (such as those defined via Object.defineProperty) are excluded from the array.
  3. String Conversion: All returned keys are strictly of the string type. If an object uses numerical keys or array indices, they are converted to strings in the resulting array.

Basic Example

const _ = require('lodash');

function Person() {
  this.name = 'Alex';
  this.role = 'Developer';
}

Person.prototype.organization = 'Tech Corp'; // Inherited property

const user = new Person();

console.log(_.keys(user));
// Output: ['name', 'role']

In the example above, 'organization' is excluded because it resides on the prototype chain, not directly on the user instance.

Handling of Different Input Types

The _.keys method handles various data types predictably:

_.keys vs. _.keysIn

Lodash provides a related method called _.keysIn. The critical distinction is:

_.keys(user);   // ['name', 'role']
_.keysIn(user); // ['name', 'role', 'organization']

Comparison with Native Object.keys()

Lodash's _.keys behaves almost identically to native Object.keys() in modern ECMAScript environments. The primary distinction is historical safety: _.keys coerces primitives, null, and undefined safely to empty arrays across all JavaScript environments, whereas legacy environments previously threw errors on non-object inputs with Object.keys().