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
TypeErrorexception.
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
}