How do I remove objects from a JavaScript associative array?
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') // truedelete 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.
All objects in JavaScript are implemented as hashtables/associative arrays. So, the following are the equivalent:
alert(myObj["SomeProperty"]);alert(myObj.SomeProperty);
And, as already indicated, you "remove" a property from an object via the delete
keyword, which you can use in two ways:
delete myObj["SomeProperty"];delete myObj.SomeProperty;
Hope the extra info helps...
None of the previous answers address the fact that JavaScript does not have associative arrays to begin with - there is no array
type as such, see typeof
.
What JavaScript has, are object instances with dynamic properties. When properties are confused with elements of an Array object instance then Bad Thingsā¢ are bound to happen:
Problem
var elements = new Array()elements.push(document.getElementsByTagName("head")[0])elements.push(document.getElementsByTagName("title")[0])elements["prop"] = document.getElementsByTagName("body")[0]console.log("number of elements: ", elements.length) // Returns 2delete elements[1]console.log("number of elements: ", elements.length) // Returns 2 (?!)for (var i = 0; i < elements.length; i++){ // Uh-oh... throws a TypeError when i == 1 elements[i].onmouseover = function () { window.alert("Over It.")} console.log("success at index: ", i)}
Solution
To have a universal removal function that does not blow up on you, use:
Object.prototype.removeItem = function (key) { if (!this.hasOwnProperty(key)) return if (isNaN(parseInt(key)) || !(this instanceof Array)) delete this[key] else this.splice(key, 1)};//// Code sample.//var elements = new Array()elements.push(document.getElementsByTagName("head")[0])elements.push(document.getElementsByTagName("title")[0])elements["prop"] = document.getElementsByTagName("body")[0]console.log(elements.length) // Returns 2elements.removeItem("prop")elements.removeItem(0)console.log(elements.hasOwnProperty("prop")) // Returns false as it shouldconsole.log(elements.length) // returns 1 as it should