1. 什么是 obj-chain-plugin-lodash
obj-chain-plugin-lodash 是一个基于 lodash 函数库实现的 npm 包,通过该包可以轻松地实现 JavaScript 对象的链式调用。
2. 安装
使用 npm 安装 obj-chain-plugin-lodash:
npm install obj-chain-plugin-lodash
3. 基本使用
3.1 引入库
const { _ } = require('obj-chain-plugin-lodash')
3.2 例子
假设我们有一个对象数组:
-- -------------------- ---- ------- ----- ------- - - - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - -- - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - -- - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - - -展开代码
3.2.1 筛选出年龄大于 14 岁的人
const newPersons = _(persons) .filter(x => x.age > 14) .value() console.log(newPersons)
运行结果:
-- -------------------- ---- ------- - - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - -- - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - - -展开代码
3.2.2 筛选出数学成绩大于 80 分的人
const newPersons = _(persons) .filter(x => x.scores.math > 80) .value() console.log(newPersons)
运行结果:
-- -------------------- ---- ------- - - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - -- - ----- ----- ---- --- ------- ----- ------- --- ------- - ----- --- -------- --- -------- -- - - -展开代码
3.2.3 求出所有人的平均体重
const avgWeight = _(persons) .map(x => x.weight) .mean() .value() console.log(avgWeight)
运行结果:
56
4. 方法详解
4.1 _.filter
- 作用:筛选出符合条件的元素
- 参数:
_.filter(collection, [predicate=_.identity])
- collection (Array|Object): 待筛选的集合。
- [predicate=_.identity] (Function): 返回值为 true 表示保留元素,返回值为 false 表示过滤元素。
- 示例:
const newPersons = _(persons) .filter(x => x.age > 14) .value()
4.2 _.map
- 作用:将集合中的每个元素按指定规则转换为新的元素
- 参数:
_.map(collection, [iteratee=_.identity])
- collection (Array|Object): 待转换的集合。
- [iteratee=_.identity] (Function): 转换规则,返回转换后的值。
- 示例:
const avgWeight = _(persons) .map(x => x.weight) .mean() .value()
4.3 _.mean
- 作用:求集合中所有元素的平均值
- 参数:
_.mean(array)
- array (Array): 待计算的数组。
- 示例:
const avgWeight = _(persons) .map(x => x.weight) .mean() .value()
5. 总结
通过使用 obj-chain-plugin-lodash 这个 npm 包,我们可以轻松地实现 JavaScript 对象的链式调用,极大地方便了我们的编程工作。在使用时,需要注意对象的类型、传递的参数等因素,同时还需要熟悉常用的 lodash 函数库方法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5f168218403f2923b035c36d