posts found in this keyword

    How to Delete a Key From an Object in JavaScript or Node.js

    How to Delete a Key From an Object in JavaScript or Node.js

    Deleting keys from an object may happen in a handful of situations. Like, in case a request contains a key-value pair that isn’t allowed to be part of the request and you still want to handle that request. You can then delete the keys not being allowed and proceed to process the request.

    This tutorial shows you how to remove one or many keys from a JavaScript object.

    Delete an Object Property in JavaScript

    JavaScript offers different ways to delete an object’s property. The way we recommend is using destructuring. We discourage using the delete operator because it can cause side effects in your code. So let’s look at both ways!

    Use Destructuring to Delete a Property From an Object

    You can remove a property from an object using destructuring in combination with the ... rest operator. Destructuring splits an object into its individual keys, and you can remove those you don’t want in the new one.

    Here’s an example of removing the group property from a user object:

    const user = { id: 1, name: 'Charizard', group: 'admin' }
    
    const { ['group']: group, ...userWithoutGroup } = user  
    console.log(userWithoutGroup)  
    // { id: 1, name: 'Charizard' }
    

    The code snippet destructures the user into a group property and everything else called userWithoutGroup.

    You can also put this functionality into a reusable utility function:

    /**
     * Returns the given `obj` without the `property`.
     *
     * @param {Object} obj
     * @param {String} property
     *
     * @returns {Object}
     */
    function withoutProperty(obj, property) {  
        const { [property]: unused, ...rest } = obj
    
      return rest
    }
    

    Then use the withoutProperty utility function like this:

    const user = { id: 1, name: 'Charizard', group: 'admin' }
    
    const userWithoutGroup = withoutProperty(user, 'group')  
    // { id: 1, name: 'Charizard' }
    

    Sweet!

    Avoid delete object[property]

    You probably know the globally available delete operator to remove a property from a JavaScript object. But be careful: deleting a property using delete mutates the original object!

    const user = { id: 1, name: 'Charizard', group: 'admin' }
    
    delete user['group']
    
    // this may cause 💥 in parts where `user.group` is used
    

    Mutating the original object may affect other parts of your application and it might be hard to debug. Especially when you’re providing a third-party library as a community plugin that mutates the objects using delete. Avoid mutating the original object.

    Enjoy!