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
}