Modelo

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

How to Delete an Item from JavaScript Object

Oct 05, 2024

When working with JavaScript objects, you may need to delete an item from the object. This can be achieved using the delete operator. The delete operator is used to remove a property from an object. Here's how you can delete an item from a JavaScript object:

```javascript

// Create an example object

let obj = {

name: 'John',

age: 30,

city: 'New York'

};

// Use the delete operator to remove an item

delete obj.city;

// The 'city' property is now removed from the object

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

```

In the example above, we have an object called `obj` with three properties: `name`, `age`, and `city`. We then use the `delete` operator to remove the `city` property from the object.

It's important to note that the `delete` operator only removes a property from an object; it does not reindex the remaining items. This means that if the object is an array, the array length will not automatically change.

Additionally, when using the `delete` operator, the property name should be specified without quotes. For example, to delete the `age` property from the `obj` object, you would write `delete obj.age` rather than `delete obj['age']`.

It's also worth mentioning that the `delete` operator returns `true` if the property is successfully deleted, and `false` if it fails (for example, if the property is non-configurable). However, in most cases, you won't need to use the return value of the `delete` operator.

In summary, the `delete` operator is a useful tool for removing properties from JavaScript objects. Just remember to use it carefully, as it does not reindex the remaining properties and may have limitations in certain scenarios. With this knowledge, you can confidently delete items from JavaScript objects when needed.

Recommend