首页 > 解决方案 > 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应该是一个字符串。我该怎么做?

标签: javascriptlodash

解决方案


使用计算属性名称来“提取”要在解构时删除的属性:

function omit(obj, attr) {
  const { [attr]: _, ...newObj } = obj;
  return newObj;
}

console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar'));


推荐阅读