Search code examples
javascriptlodash

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?


Solution

  • 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']));