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:
- Own Properties Only: The method inspects only properties directly assigned to the target object. It ignores inherited properties from the object's prototype chain.
- Enumerable Properties Only: Properties created with
enumerable: false(such as those defined viaObject.defineProperty) are excluded from the array. - String Conversion: All returned keys are strictly
of the
stringtype. 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:
- Arrays: When passed an array,
_.keysreturns the indices as strings._.keys(['a', 'b', 'c']); // Output: ['0', '1', '2'] - Strings: Strings are treated as array-like objects,
returning their character index positions.
_.keys('hi'); // Output: ['0', '1'] - Primitives (Numbers, Booleans, null, undefined):
Primitives without enumerable properties return an empty array without
throwing a runtime error.
_.keys(123); // Output: [] _.keys(null); // Output: []
_.keys vs.
_.keysIn
Lodash provides a related method called _.keysIn. The
critical distinction is:
_.keys: Returns an array of own enumerable string properties._.keysIn: Returns an array of own and inherited enumerable string properties.
_.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().