How Lodash _.get Handles Spaces in Bracket Paths

Lodash’s _.get method safely retrieves deeply nested object values using bracket notation with explicit spaces by parsing string paths into static property arrays via deterministic regular expressions rather than dynamic code execution. By converting paths like user['first name'] into normalized keys through its internal stringToPath utility, Lodash eliminates the risk of code injection, avoids the pitfalls of JavaScript’s native eval, and guarantees that property names containing spaces are treated strictly as string literals.

Path Parsing via stringToPath

When a string path containing bracket notation is passed to _.get, the method delegates the parsing to an internal helper named stringToPath. Instead of executing the string as JavaScript code, Lodash uses a specialized regular expression to tokenize the string into discrete property segments.

The parser specifically looks for matching brackets containing single- or double-quoted strings:

When property names contain spaces—such as data['order details']—the regular expression isolates the text inside the quotes, strips the enclosing quote marks, and outputs the literal string "order details".

Preventing Dynamic Code Execution

In native JavaScript, bracket notation inside an evaluated string or template can pose security risks if user-supplied input is processed through mechanisms like eval() or new Function(). Lodash avoids this entirely:

  1. No Evaluation: Bracket contents are never evaluated as JavaScript expressions. An expression like data['user ' + id] is not calculated dynamically; it is parsed literally according to the regex tokens.
  2. Literal Matching: The string within the brackets is treated strictly as an object key identifier.
  3. Prototype Hardening: Recent versions of Lodash include guards against prototype pollution during path resolution, ignoring or safely bypassing sensitive properties like __proto__, constructor, and prototype.

Iterative Object Traversal

Once stringToPath converts the path string into an array of keys (e.g., ["account", "billing address", "street"]), _.get iterates through the keys sequentially using a standard while loop.

At each step of the traversal:

The Array Path Alternative

While Lodash securely parses string-based bracket notation containing spaces, passing property paths directly as an array bypasses string tokenization altogether:

// String representation parsed securely via regex:
_.get(userProfile, "['personal details']['first name']");

// Direct array alternative bypassing path parsing:
_.get(userProfile, ['personal details', 'first name']);

Supplying an array of strings ensures that spaces, punctuation, and special characters are preserved exactly as intended without relying on the internal path cache or regular expression matching.