How can I remove a key from a JavaScript object?

How can I remove a key from a JavaScript object?

For example, consider the following object:

var thisIsObject = {
    'Cow': 'Moo',
    'Cat': 'Meow',
    'Dog': 'Bark'
};

I want to create a function that removes a key by its name, like this: removeFromObjectByKey(‘Cow’);

How can I achieve this using JavaScript?

You can use the delete operator to remove a property from an object.

function removeFromObjectByKey(key) {
    delete thisIsObject[key];
}

// Example usage
removeFromObjectByKey('Cow');
console.log(thisIsObject); // Output: { 'Cat': 'Meow', 'Dog': 'Bark' }

You can create a new object that excludes the key you want to remove by using destructuring and the spread operator.

function removeFromObjectByKey(key) {
    const { [key]: _, ...newObject } = thisIsObject; // Ignore the key to be removed
    return newObject;
}

// Example usage
const updatedObject = removeFromObjectByKey('Cow');
console.log(updatedObject); // Output: { 'Cat': 'Meow', 'Dog': 'Bark' }

You can iterate through the object’s keys and build a new object without the specified key:

function removeFromObjectByKey(key) {
    const newObject = {};
    Object.keys(thisIsObject).forEach((k) => {
        if (k !== key) {
            newObject[k] = thisIsObject[k];
        }
    });
    return newObject;
}

// Example usage
const updatedObject = removeFromObjectByKey('Cow');
console.log(updatedObject); // Output: { 'Cat': 'Meow', 'Dog': 'Bark' }