Skip to content

Lodash - 集合

Lodash 精于处理集合(collections),集合包括数组(arrays)和对象(objects)。其集合函数提供了强大而便捷的方式来迭代(iterate)、过滤(filter)、分组(group)、排序(sort)和转换(transform)数据,通常比原生 JavaScript 方法更灵活。

一个主要特性是 Lodash 能够接受各种 ‘iteratee’ 简写方式(函数、字符串属性名、用于匹配的对象或用于匹配的数组对),从而简化了常见操作。

虽然原生的 Array 方法如 map、filter、reduce、find、some、every 和 includes 很强大,但 Lodash 提供了适用于数组和对象值的等效方法,以及其他一些有用的方法:

方法与语法描述与主要特性
forEach / each
.forEach(collection, [iteratee=.identity])
遍历 collection 中的元素,为每个元素执行 iteratee。适用于数组和对象。原生等效方法:Array.prototype.forEach(仅适用于数组)、for...in 或 Object.keys/values/entries().forEach(适用于对象)。
map
.map(collection, [iteratee=.identity])
通过对 collection 中的每个元素运行 iteratee 来创建一个值数组。适用于数组和对象(映射值)。原生等效方法:Array.prototype.map(仅适用于数组)。
filter
.filter(collection, [predicate=.identity])
遍历 collection 中的元素,返回 predicate 返回 truthy 的所有元素组成的数组。适用于数组和对象(基于值过滤)。原生等效方法:Array.prototype.filter(仅适用于数组)。
reject
.reject(collection, [predicate=.identity])
_.filter 的反向操作;返回 predicate 返回 falsey 的元素。
find
.find(collection, [predicate=.identity], [fromIndex=0])
遍历 collection 中的元素,返回 predicate 返回 truthy 的第一个元素。适用于数组和对象。原生等效方法:Array.prototype.find(仅适用于数组)。
reduce
.reduce(collection, [iteratee=.identity], [accumulator])
通过对 collection 中的每个元素运行 iteratee,将 collection 简化(reduce)为一个单一值。适用于数组和对象。原生等效方法:Array.prototype.reduce(仅适用于数组)。
every
.every(collection, [predicate=.identity])
检查 predicate 是否对 collection 的所有元素都返回 truthy。适用于数组和对象。原生等效方法:Array.prototype.every(仅适用于数组)。
some
.some(collection, [predicate=.identity])
检查 predicate 是否对 collection 的任一元素返回 truthy。适用于数组和对象。原生等效方法:Array.prototype.some(仅适用于数组)。
includes
_.includes(collection, value, [fromIndex=0])
检查 collection 中是否包含 value。使用 SameValueZero 进行相等比较。适用于数组、对象(检查值)和字符串。原生等效方法:Array.prototype.includes、String.prototype.includes。
groupBy
.groupBy(collection, [iteratee=.identity])
创建一个对象,其键由对 collection 的每个元素运行 iteratee 的结果生成。每个键对应的值是生成该键的所有元素的数组。
keyBy
.keyBy(collection, [iteratee=.identity])
创建一个对象,其键由对 collection 的每个元素运行 iteratee 的结果生成。每个键对应的值是生成该键的最后一个元素。
orderBy
.orderBy(collection, [iteratees=[.identity]], [orders])
根据 iteratees 和相应的 orders(‘asc’ 或 ‘desc’)对 collection 中的元素进行排序。它比 Array.prototype.sort 更强大,因为它允许使用多个排序条件并能可靠地处理复杂数据类型。
sortBy
.sortBy(collection, [iteratees=[.identity]])
orderBy 的简化版本,用于基于一个或多个条件进行升序排序。
partition
.partition(collection, [predicate=.identity])
将元素分割成两个组的数组,第一个组包含 predicate 返回 truthy 的元素,第二个组包含其余元素。
sample
_.sample(collection)
从 collection 中获取一个随机元素。
sampleSize
_.sampleSize(collection, [n=1])
从 collection 中获取 n 个随机元素。
shuffle
_.shuffle(collection)
创建一个打乱顺序的值数组,使用 Fisher-Yates 洗牌算法的一个版本。
size
_.size(collection)
通过返回类数组值的长度或对象的自有可枚举字符串键属性的数量来获取 collection 的大小。原生等效方法:Array.prototype.length、Object.keys(obj).length。
flatMap
.flatMap(collection, [iteratee=.identity])
通过对 collection 中的每个元素运行 iteratee 并展平映射结果,创建一个展平的值数组。原生等效方法:Array.prototype.flatMap(仅适用于数组)。
flatMapDeep
.flatMapDeep(collection, [iteratee=.identity])
类似于 _.flatMap,但递归地展平映射结果。
flatMapDepth
.flatMapDepth(collection, [iteratee=.identity], [depth=1])
类似于 _.flatMap,但将映射结果展平至指定 depth 深度。

许多 Lodash 集合方法接受 iteratee 或 predicate 参数的简写语法:

  • 字符串: _.map(users, 'name') (获取 ‘name’ 属性)
  • 对象: _.filter(users, { active: true }) (匹配具有 active: true 属性的对象)
  • 数组: _.find(users, ['name', 'Alice']) (匹配 name 为 ‘Alice’ 的对象)
import _ from 'lodash-es';
const users = [
{ 'name': 'Alice', 'role': 'admin', 'active': true },
{ 'name': 'Bob', 'role': 'editor', 'active': true },
{ 'name': 'Charlie', 'role': 'editor', 'active': false },
{ 'name': 'David', 'role': 'admin', 'active': true }
];
// 按 role 分组用户
const usersByRole = _.groupBy(users, 'role');
// usersByRole: { admin: [...], editor: [...] }
// 获取活跃用户的名称
const activeUserNames = _(users)
.filter('active') // 简写形式: { active: true }
.map('name') // 简写形式: user => user.name
.value(); // 执行链式调用
// activeUserNames: ['Alice', 'Bob', 'David']
// 创建一个将用户名称映射到其角色的对象
const nameToRoleMap = _.keyBy(users, 'name');
// nameToRoleMap: { Alice: { name: 'Alice', ... }, Bob: { ... }, ... }
const simpleMap = _.mapValues(nameToRoleMap, 'role');
// simpleMap: { Alice: 'admin', Bob: 'editor', Charlie: 'editor', David: 'admin' }
console.log('Users by Role:', usersByRole);
console.log('Active User Names:', activeUserNames);
console.log('Role Map:', simpleMap);

Lodash 集合方法提供了简洁而强大的方式来操作数据结构,这在 Web 开发、数据分析和通用脚本任务中非常常见。