How do I remove objects from a javascript associative array?

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

Solutions/Answers:

Solution 1:

Use the “delete” keyword in Javascript.

delete myArray["lastname"];

EDIT:

In some JavaScript engine, the delete keyword might hurt performance as it will undo compile / JIT optimization.

http://www.html5rocks.com/en/tutorials/speed/v8/
http://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/

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 removes deletes the object but still keeps the array length same.

To remove 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 Arrays) can be used this way. However, do not expect for standard JS array functions (pop, push,…) 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.

Solution 6:

Use method splice to completely remove item from an object array:

Object.prototype.removeItem = function (key, value) {
    if (value == undefined)
        return;

    for (var i in this) {
        if (this[i][key] == value) {
            this.splice(i, 1);
        }
    }
};

var collection = [
    { id: "5f299a5d-7793-47be-a827-bca227dbef95", title: "one" },
    { id: "87353080-8f49-46b9-9281-162a41ddb8df", title: "two" },
    { id: "a1af832c-9028-4690-9793-d623ecc75a95", title: "three" }
];

collection.removeItem("id", "87353080-8f49-46b9-9281-162a41ddb8df");