Lodash _.values: Extracting Object Values in JavaScript
This article provides an overview of the _.values method
in the Lodash JavaScript library, explaining how it extracts an array of
values from an object. You will learn the mechanics behind the function,
its syntax, how it handles different data structures and edge cases, and
how it compares to native JavaScript alternatives like
Object.values().
What is Lodash
_.values?
The _.values method is a utility function in the Lodash
library that retrieves the own enumerable string-keyed property values
of an object and returns them as a new JavaScript array. It is
particularly useful for transforming structured object data into an
iterable list for sorting, filtering, or mapping.
Syntax
_.values(object)object: The target object from which property values are to be retrieved.- Returns: A new array containing the extracted values.
How _.values Extracts
Data
When an object is passed to _.values, Lodash performs
several internal checks to extract the data safely:
- Checks for Enumerable Properties: The method inspects the object and identifies keys that belong directly to the object (own properties), ignoring non-enumerable properties and properties inherited through the prototype chain.
- Maintains Property Order: The values are inserted
into the resulting array in the same order as a standard
for...inloop orObject.keys()call would iterate over them. - Returns a New Array: It creates a flat array containing only the values corresponding to those keys.
Basic Example
const _ = require('lodash');
const character = {
name: 'Geralt',
class: 'Witcher',
level: 40
};
const values = _.values(character);
console.log(values);
// Output: ['Geralt', 'Witcher', 40]Handling Edge Cases and Data Types
A key feature of _.values is its defensive programming
design, which prevents runtime errors when handling irregular
inputs:
- Null and Undefined: If
nullorundefinedis passed,_.valuesdoes not throw an error. Instead, it safely returns an empty array ([]). - Strings: If a string is provided, Lodash converts the string into an array of its individual characters.
- Arrays: Passing an array returns a shallow duplicate of that array's values.
- Numbers and Booleans: Primitive types that do not possess enumerable properties will return an empty array.
console.log(_.values(null)); // Output: []
console.log(_.values('cat')); // Output: ['c', 'a', 't']
console.log(_.values([1, 2, 3])); // Output: [1, 2, 3]
console.log(_.values(42)); // Output: []Lodash
_.values vs. Native Object.values()
Modern JavaScript includes the native Object.values()
method, which performs a similar task. However, Lodash's
_.values provides built-in null-safety:
Object.values(null)throws aTypeError: Cannot convert undefined or null to object._.values(null)safely evaluates to[].
Because of this built-in defensive handling, _.values is
often favored in functional pipelines where input shapes are dynamic or
cannot be guaranteed to be non-null.