Add Object.splice Method

The dynamic management of object properties is a frequent necessity in programming. Currently, using the delete operator to remove properties one by one is not flexible enough. To improve the convenience of object manipulation, I propose adding the Object.splice method.

Description

The Object.splice method allows developers to delete multiple object properties at once and optionally add new properties. The method returns an object containing all the deleted property key-value pairs.

Example

const myObject = { a: 1, b: 2, c: 3, d: 4 }

// Delete 'b' and 'd', and add new properties 'e' and 'f'
const deleted = Object.splice(myObject, ['b', 'd'], { e: 5, f: 6 })

console.log('Deleted:', deleted) // { b: 2, d: 4 }
console.log('After:', myObject)  // { a: 1, c: 3, e: 5, f: 6 }

Syntax

Object.splice(obj, keysToDelete, ...itemsToAdd)

Parameters

  • obj:The object to be manipulated.
  • keysToDelete:An array of strings containing the keys of properties to delete.
  • ...itemsToAdd:A variable number of objects containing the key-value pairs to add.

Return Value

  • An object containing all the deleted property key-value pairs.

Throws Exception

  • If attempting to delete a non-configurable property, throws a TypeError exception.

Implementation

Object.splice = (obj, keysToDelete, ...itemsToAdd) => {
    const deletedItems = {}
    for (const key of keysToDelete) {
        deletedItems[key] = obj[key]
        if (!delete obj[key]) {
            throw new TypeError(`Cannot delete property '${key}' of #<Object>`)
        }
    }
    Object.assign(obj, ...itemsToAdd)
    return deletedItems
}

I wouldn't personally want to see any new mutating methods be added to the language.

You may be interested in https://github.com/tc39/proposal-object-pick-or-omit, however.

Not sure it's a good idea to implement new features that encourage bad practices
if you find yourself deleting properties frequently there's a good chance a different data structure like Map is better suited. In other cases, setting the property to null makes more sense. In any and all cases, using delete is the clear-cut worst choice for performance, and a splice method won't fix that

1 Like