我一直在寻找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
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经找到了这个解决方案:
let { attr, ...newObj } = obj;
Run Code Online (Sandbox Code Playgroud)
但它只有在attr已知时才有效。我想attr是动态的,所以attr应该是一个字符串。我该怎么做?
该_.omit()功能支持排除多个按键。该函数接受参数列表、键数组或参数和数组的组合。要保留该功能,您可以使用剩余参数,将它们展平为Set,通过 将对象转换为条目数组Object.entries(),对其进行过滤,然后使用 转换回对象Object.fromEntries()。
function omit(obj, ...keys) {
const keysToRemove = new Set(keys.flat()); // flatten the props, and convert to a Set
return Object.fromEntries( // convert the entries back to object
Object.entries(obj) // convert the object to entries
.filter(([k]) => !keysToRemove.has(k)) // remove entries with keys that exist in the Set
);
}
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar'));
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar', 'baz'));
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, ['bar', 'baz']));
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar', ['baz']));Run Code Online (Sandbox Code Playgroud)
使用计算属性名称“提取”要在解构时删除的属性:
function omit(obj, attr) {
const { [attr]: _, ...newObj } = obj;
return newObj;
}
console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
567 次 |
| 最近记录: |