Iterate collections with Lodash
Lodash collection methods accept arrays, objects and strings alike, so one call style covers all three.
How it works
- One API for three shapes.
_.mapruns on an array, on a plain object (getting each value and key) and on a string (getting each character). [1] - Walk an object.
_.forEach(prices, (price, item) => ...)visits every key of the object and prints a line for each. [1] - Filter by property.
_.filter(tasks, { done: false })uses an object as the test and keeps tasks whosedonematches. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import _ from 'lodash';
// Arrays
const nums = [1, 2, 3, 4];
console.log('array map x10:', JSON.stringify(_.map(nums, (n) => n * 10)));
// Objects: callback gets (value, key)
const prices = { apple: 1.2, bread: 2.5, cheese: 6 };
console.log('object forEach:');
_.forEach(prices, (price, item) => console.log(` ${item.padEnd(7)} $${price.toFixed(2)}`));
console.log('object map:', JSON.stringify(_.map(prices, (price, item) => `${item}=${price}`)));
// Strings: iterated character by character
console.log('string map:', _.map('lodash', (ch) => ch.toUpperCase()).join('-'));
// Filter with an object as the test
const tasks = [
{ title: 'Write docs', done: true },
{ title: 'Fix bug', done: false },
{ title: 'Ship release', done: false },
];
const open = _.filter(tasks, { done: false });
console.log('open tasks:', open.map((t) => t.title).join(', '));
console.log('open count:', open.length, 'of', tasks.length);
Swap the word in the string example and the per-letter output changes. Code written by AgentGid [1].
Swap the word in the string example and the per-letter output changes. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with lodash 4.18.1. Needs WebGL.
More Lodash examples
Default values with _.defaults Split arrays with _.partition Read nested values with _.at Compose functions with Lodash
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.