Using Lodash sumBy for Nested Object Properties
Totaling values within arrays of complex JavaScript objects often
requires multi-line, boilerplate-heavy loops or native
reduce implementations that must explicitly handle missing
or undefined fields. The Lodash library simplifies this challenge
through its _.sumBy utility method. By accepting property
paths or custom iteratee functions, _.sumBy enables
developers to calculate sums across deeply nested structures cleanly,
safely, and with minimal code.
The Challenge with Native JavaScript
In standard JavaScript, summing a nested property across an array of
objects typically relies on Array.prototype.reduce().
Consider an array of order items where each item contains a nested
pricing object:
const orders = [
{ id: 1, pricing: { total: 45.50 } },
{ id: 2, pricing: { total: 12.00 } },
{ id: 3, pricing: { total: 99.99 } }
];
const total = orders.reduce((sum, order) => {
return sum + (order.pricing?.total || 0);
}, 0);While functional, this approach requires explicit initializers, optional chaining to prevent runtime errors if an object is malformed, and manual fallback handling for non-numeric values.
How _.sumBy
Streamlines the Process
The _.sumBy method calculates the sum of values produced
by each element in a collection. It takes two primary arguments:
- Collection: The array or object to iterate over.
- Iteratee: The criterion used to extract or compute the numerical value to be summed.
1. Using String Path Notation
Lodash supports dot-notation path strings as iteratees. This allows you to target nested keys directly without writing a custom callback function:
const _ = require('lodash');
const orders = [
{ id: 1, pricing: { total: 45.50 } },
{ id: 2, pricing: { total: 12.00 } },
{ id: 3, pricing: { total: 99.99 } }
];
const grandTotal = _.sumBy(orders, 'pricing.total');
// Output: 157.49Lodash internally resolves the 'pricing.total' path for
every element and accumulates the sum automatically.
2. Built-in Safety for Missing Data
If any nested key in the collection is null,
undefined, or unresolvable, _.sumBy handles it
gracefully instead of throwing a TypeError:
const irregularOrders = [
{ id: 1, pricing: { total: 50 } },
{ id: 2, pricing: null },
{ id: 3 }
];
const safeTotal = _.sumBy(irregularOrders, 'pricing.total');
// Output: 50Lodash treats missing, null, or non-numeric values as
zero in the accumulation, eliminating the need for defensive manual
checks.
3. Using Custom Iteratee Functions
When values require transformation, type casting, or multi-property
calculations before summing, _.sumBy accepts a
function:
const inventory = [
{ item: 'A', stock: { warehouse: 5, retail: '10' } },
{ item: 'B', stock: { warehouse: 2, retail: 3 } }
];
const totalUnits = _.sumBy(inventory, (entry) => {
return entry.stock.warehouse + Number(entry.stock.retail);
});
// Output: 20Conclusion
By abstracting away nested null checks, accumulation initializers,
and traversal boilerplate, _.sumBy converts multi-step
reduction logic into a single, declarative line of code. It enhances
both readability and safety when aggregating data across complex
JavaScript object hierarchies.