Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to lodash omit

I would like to delete a property and return a new object without mutating the original object.

I know we can do this easily with Lodash like this:

const profile = { name: 'Maria', age: 30 }
_.omit(profile, name) // it returns a new object without the property name {age: 30}

However, I would like to know if it's possible to do it with vanilla JavaScript without assigning that value to undefined or using a filter?

like image 228
Chumpocomon Avatar asked Dec 22 '19 19:12

Chumpocomon


1 Answers

For a single key you can destructure the object, and use computed property with rest to create an object without the property:

const omitSingle = (key, { [key]: _, ...obj }) => obj
const profile = { name: 'Maria', age: 30 }

const result = omitSingle('name', profile)

console.log(result)

To omit multiple properties, you can convert the object to [key, value] pairs, filter the pairs according to the listed keys array, and then convert back to an object via Object.fromEntries():

const omit = (keys, obj) => 
  Object.fromEntries(
    Object.entries(obj)
      .filter(([k]) => !keys.includes(k))
  )
  
const profile = { name: 'Maria', gender: 'Female', age: 30 }

const result = omit(['name', 'gender'], profile)

console.log(result)
like image 88
Ori Drori Avatar answered Oct 18 '22 21:10

Ori Drori