How to Remove Objects from a JavaScript Associative Array

JavaScript objects can be accepted as associative arrays mapping keys to values. To remove a key from an object in JavaScript you can use the delete operator:

const obj = {
  siteName: 'w3docs'
}
console.log(obj.hasOwnProperty('siteName')); // true
delete obj['siteName']
console.log(obj.hasOwnProperty('siteName')); // false

When the delete is applied to an index property of an Array, you will create a sparsely populated array which is an array with a missing index.

When working with instances of Array, if you do not want to create a sparsely populated array, then you can use the Array#splice or Array#splice methods.

Associative Arrays

Arrays that has named indexes are called associative arrays. In JavaScript, arrays always use numbered indexes. Associative arrays are object literals.

The delete Operator

The delete operator is used to remove a key from an object. It is automatically released if no more references to the same key are held. It will return true if the deletion was successful, if not it will return false. However, if the key which you are trying to delete does not exist, the operator won't have an effect and will return true.


Do you find this helpful?

Related articles