javascript - Lodash'es `omit()` 的纯 JavaScript 替换
问题描述
我一直在寻找omit()
仅使用 JavaScript 的 Lodash 替代品。这就是我想要实现的目标:
function omit(obj, attr) {
// @obj: original object
// @attr: string, attribute I want to omit
// return a new object, do not modify the original object
}
到目前为止,我已经找到了这个解决方案:
let { attr, ...newObj } = obj;
但它只有在attr
已知的情况下才有效。我想要attr
动态的,所以attr
应该是一个字符串。我该怎么做?
解决方案
使用计算属性名称来“提取”要在解构时删除的属性:
function omit(obj, attr) {
const { [attr]: _, ...newObj } = obj;
return newObj;
}
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar'));
推荐阅读
- node.js - 无法使用 Node.js 和 React Native 将文件上传到服务器
- html - 本地背景图片不显示,但如果我用网络上的一张替换它,它确实有效
- typescript - 打字稿单元测试私有和受保护方法
- react-native - 使用 React Native 的 WebView 获取 JSON 的正确方法
- python - Django:如何在模板中显示模型字段的总和
- spring - 春季安全。主体=匿名用户,类型=AUTHORIZATION_FAILURE
- user-experience - 为什么你不应该阻止右键单击网站
- reactjs - .env 显示不正确的值
- c - valgrind 显示内存泄漏。我如何阻止泄漏?
- xcode - 在 Xcode 中使用 AppleScript App 读取文本文件