How do I remove objects from a JavaScript associative array?
Solution 1
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.
Solution 2
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...
Solution 3
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 2
delete 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 2
elements.removeItem("prop")
elements.removeItem(0)
console.log(elements.hasOwnProperty("prop")) // Returns false as it should
console.log(elements.length) // returns 1 as it should
Solution 4
That only deletes the object, but it still keeps the array length the same.
To remove the element from the array, you need to do something like:
array.splice(index, 1);
Solution 5
While the accepted answer is correct, it is missing the explanation why it works.
First of all, your code should reflect the fact that this is not an array:
var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;
Note that all objects (including Array
s) can be used this way. However, do not expect for standard JavaScript array functions (pop, push, etc.) to work on objects!
As said in accepted answer, you can then use delete
to remove the entries from objects:
delete myObject["lastname"]
You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.
Admin
Updated on July 08, 2022Comments
-
Admin almost 2 years
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.)
-
MooGoo almost 14 yearsIndeed, but in this case an array is not being used, just a plain old object, thus it has no length or splice method.
-
Kip about 13 yearsshould be noted that the dot notation doesn't work if the property isn't a simple term. i.e.
myObj['some;property']
works, butmyObj.some;property
wouldn't (for obvious reasons). Also it might not be obvious that you can use a variable in the bracket notation, i.e.var x = 'SomeProperty'; alert(myObj[x])
-
Saul about 12 yearsThis will cause problems if used on an Array object instance to remove an existing element, e.g.
delete myArray[0]
. See stackoverflow.com/a/9973592/426379 and Deleting array elements -
Gottox about 12 yearsWhat problems will be caused?
-
Saul about 12 years@Gottox - The
length
property of an Array object remains unchanged. -
johndodo about 12 years@Saul: there would be problems if
myArray
was really used as an array - but it is not (myArray
is unfortunate name), it is an object. So in this casedelete
is OK. Note that even if it was created asnew Array()
and used as associative array it would still be OK. Your warning is still something to be aware of if one is using real arrays though. -
Saul about 12 years@johndodo - True. That is why I started my initial comment with This will cause problems if used on an Array object instance. I nevertheless prefer an approach which performs correctly in all cases, see my answer below.
-
johndodo about 12 years@Saul: see my comment below your answer.
-
johndodo about 12 yearsThis solution has two issues: it hides the fact that arrays and objects are entirely different beasts in JS (you know it, but apparently OP doesn't) and it uses prototypes. OP would be better off if he learned about arrays and objects (and would name his variables accordingly) - trying to hide the differences between the two will only get him in more trouble. IMHO of course.
-
Saul about 12 years@johndodo - all
Array
s in JS are objects, trytypeof new Array();
ortypeof []
to verify.Array
is simply a certain kind of an object and not at all a "different beast". In JS, objects are distinguished by their constructor name and prototype chain, see Prototype-based programming. -
johndodo about 12 yearsYou are missing the point. I know that arrays are objects too, but that doesn't mean it is wise to use them as such. Programmer should decide if he wants to use something as array (with push, pop, [],...) or as object/"associative array". Mix and match is not a good recipe, precisely because of the problems your solution is trying to hide. If you decide in advance which design pattern to use (array or object) there will be no such problems.
-
Saul about 12 years@johndodo - What problems specifically are you talking about? The purpose of above code is to adresses the deficiency
delete
operator has in regards toArray
by providing a simple polymorphic function. -
Admin over 11 years@kamal - no. What you want can be found here
-
Ivan Kochurkin over 11 yearsIs it properly to use it if element does not exists in array?
-
rodolfo42 about 10 yearsVery good answer. I would only advise anyone reading this that Arrays in javascript should not be abstracted as 'maps', but rather 'lists'. That's because you should not try to have control over the index of the elements when using arrays. If you try that...well, just don't :D
-
whiterook6 about 10 yearsDoes this also delete referenced objects? What if myArray["lastname"] was a reference?
-
Cristopher Van Paul almost 10 years@whiterook6 There is nothing "destructor" in Javascript. The behavior of "delete" is simple and just make the following variable undefined.
-
pronebird almost 10 yearsIt works on objects. Arrays will have undefined values.
-
Kevin Wheeler almost 9 yearsWhat happens when you try to delete an attribute that doesn't exist?
-
John Dvorak almost 9 years"All objects in JavaScript are implemented as hashtables/associative arrays. " - false. V8 prefers to store an object as a hidden class + densely packed fields. Only if you do weird stuff to them (such as removing fields) it gives up and uses a hash map behind the scenes.
-
Jason Bunting over 8 years@JanDvorak - hey, you recognize when this answer was originally written, yeah? That description was and still is sufficient for most purposes. That said, I understand being tediously pedantic. :)
-
Hussain almost 7 yearsthis is a more generic solution, can be added to your js file and the method will be available to all arrays, not just one array.
-
Edward over 6 yearsperfect explanation. I used filter to achieve the desired result. Would you explain how the return item works to remove the object from the array. I'm assuming it returns the array as long as it doesn't include the string you included.
-
Drenai about 6 years@Andreaa Panagiotidis Except when we're not talking about Arrays, in which case it's wrong 100% of the time 🙂
-
Hassan Baig about 6 yearsThis could be useful in cases where one isn't sure whether the key exists in the dictionary, but wants to sanitize it in case it does. Correct me if I'm wrong Amytis.
-
Vaishnavi Patel over 5 yearsWhat if I want to delete 'lastname' from 3D array?
-
Code Maniac almost 5 yearsWhy not use filter instead ? this is a perfect use case for filter
-
Ben Aston about 4 yearsJavaScript does not have multidimensional arrays. Nested arrays are possible, however.
-
Ben Aston about 4 years
delete
does not have a deficiency.delete
is designed to remove properties. That's it. Applying the delete operator to an index of an array removes that index. What more need it do? You are left with a sparse array, which is a feature of the language. If you don't want a sparse array, don't delete the index: usesplice
orpop
. -
Saul about 4 years@BenAston Yeah looking at it now after all these years I agree. Sparse arrays are indeed a feature of the language and delete is indeed simply designed to delete properties. Now all I need to do is to figure out how to find the motivation for deleting an answer which has netted me around 450 points of reputation :-)
-
Saul about 4 years@BenAston Yes.. or 442 points to be super exact. So who knows, maybe some of those upvotes were given not to the "workaround" but to some useful insights in general :-) In any case, thanks for noticing the misinformed parts and clarifying!