How do I remove objects from a JavaScript associative array?

Andrew picture Andrew · Dec 6, 2008 · Viewed 607.4k times · Source

Suppose I have this code:

var myArray = new Object();
myArray["firstname"] = "Bob";
myArray["lastname"] = "Smith";
myArray["age"] = 25;

Now if I wanted to remove "lastname"?....is there some equivalent of myArray["lastname"].remove()?

(I need the element gone because the number of elements is important and I want to keep things clean.)

Answer

Dennis C picture Dennis C · Dec 6, 2008

Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.

To remove a property from an object in JavaScript you use the delete operator:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).

When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.

Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.

Using the delete operator can affect JavaScript engines' ability to optimise code.