[Javascript] Build lodash.omitBy and lodash.pickBy with Object.fromEntries + Object.entry (isomorphism)
JavaScript and with object build entry lodash
2023-09-14 09:00:47 时间
_.omitBy
and its sibling _.pickBy
are popular utilities which apply filter-like functionality to objects. Both of them accept a function to determine if a given entry in the object should be included in the output object. This lesson will demonstrate an approach to build both of these utilities from a single function using the combo of Object.entries
and Object.fromEntries
.
Object.entries
converts an object into an array of key, value pairs. We couple that with the native Array filter method, to create a generate filter()
method that works on objects. Once we've filtered our object we use Object.fromEntries
to convert the array back into an object. This works great for both omitBy
and pickBy
const entryISO = (fn, obj) => Object.fromEntries(Object.entries(obj).filter(fn)); const obj = {a: 1, b: 2, c: 3, d: 4, e: 5}; const omitBy = fn => obj => entryISO(([key, val]) => !fn(val, key), obj); const pickBy = fn => obj => entryISO(([key, val]) => fn(val, key), obj); const lg = num => val => val > num; const largetThanTwo = lg(2); const omitValuesLargerThanTwo = omitBy(largetThanTwo); const pickValuesLargerThanTwo = pickBy(largetThanTwo); console.log(omitValuesLargerThanTwo(obj)) // { a: 1, b: 2 } console.log(pickValuesLargerThanTwo(obj)) // { c: 3, d: 4, e: 5 }
相关文章
- javascript 高级教程 视频_精通JavaScript
- 「设计模式 JavaScript 描述」策略模式
- javascript ES6 Proxy
- 如何用JavaScript实现备案不关站,非工作时间还能正常显示
- JavaScript学习总结(十六)——Javascript闭包(Closure)详解编程语言
- etMySQL and JavaScript—Secure the Future of the Internet(jsmysqlin)
- MySQL中AND的使用方法及含义解析(mysql中and的含义)
- Oracle中使用AND运算符的示例分析(oracle中and用法)
- 关于javascript函数的几个话题
- Javascript常用运算符(Operators)-javascript基础教程
- JavaScript学习技巧
- JavaScript设计模式富有表现力的Javascript(一)
- JavaScript下利用fso判断文件是否存在的代码
- javascript中运用闭包和自执行函数解决大量的全局变量问题
- javascript中直接写php代码的方法
- 利用noesis.Javascript开源组件.Net中执行javascript脚本
- javascript事件冒泡详解和捕获、阻止方法
- 你可能不知道的JavaScript的newFunction()方法
- javascript框架设计读书笔记之数组的扩展与修复
- JavaScript中伪协议javascript:使用探讨
- Javascript基础教程之数据类型(数值Number)