Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure JavaScript replacement for Lodash'es `omit()`

I have been looking for a replacement for Lodash omit() using only JavaScript. This is what I want to achieve:

function omit(obj, attr) {
  // @obj: original object
  // @attr: string, attribute I want to omit
  // return a new object, do not modify the original object
}

So far, I have found this solution:

let { attr, ...newObj } = obj;

But it only works if attr is known. I want attr to be dynamic, so attr should be a string. How can I do it?

like image 960
Tera Mind Avatar asked Jan 01 '23 12:01

Tera Mind


2 Answers

The _.omit() function supports excluding multiple keys. The function accepts a list of parameters, an array of keys, or a combination of a parameters and arrays. To preserve that functionality, you can use rest parameters, flatten them to a Set, convert the object to an array of entries via Object.entries(), filter it, and then convert back to an object using 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']));
like image 53
Ori Drori Avatar answered Jan 03 '23 01:01

Ori Drori


Use a computed property name to "extract" the property you want to remove while destructuring:

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

console.log(omit({ foo: 'foo', bar: 'bar', baz: 'baz' }, 'bar'));
like image 44
CertainPerformance Avatar answered Jan 03 '23 02:01

CertainPerformance