Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Delete an Item from Object in JavaScript

Sep 30, 2024

In JavaScript, you can delete an item from an object using the delete keyword. To do this, you can specify the key of the item you want to remove from the object. Here's an example of how to delete an item from an object:

```javascript

// Create an object

let myObj = {

name: 'John',

age: 30,

city: 'New York'

};

// Delete the 'city' item from the object

delete myObj.city;

// The updated object will now look like this

console.log(myObj); // Output: { name: 'John', age: 30 }

```

In the above example, we created an object called `myObj` with three key-value pairs. We then used the delete keyword to remove the 'city' item from the object. After deleting the item, when we log the updated object to the console, we can see that the 'city' item has been successfully removed.

It's important to note that when you delete an item from an object using the delete keyword, the object's length property will not be affected. This means that the size of the object will remain the same, even after removing an item.

Additionally, if you try to access the deleted item after using the delete keyword, it will return undefined, as the item no longer exists in the object.

It's also worth mentioning that the delete keyword is specific to objects and cannot be used to delete variables or functions. It's solely used for removing items from objects.

In summary, using JavaScript's delete keyword allows you to easily remove an item from an object. By specifying the key of the item you want to delete, you can effectively modify the object to fit your needs. This comes in handy when you need to update or clean up data within your objects. Now that you know how to delete an item from an object in JavaScript, you can confidently manage and manipulate your object data with ease.

Recommend