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)

How _.values Extracts Data

When an object is passed to _.values, Lodash performs several internal checks to extract the data safely:

  1. 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.
  2. Maintains Property Order: The values are inserted into the resulting array in the same order as a standard for...in loop or Object.keys() call would iterate over them.
  3. 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:

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:

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.