javascriptarraysassociative-arrayassociative

How do I remove objects from a JavaScript associative array?


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.)


Solution

  • 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.