How to remove a property from an object?

Currently an event is set on checkboxes, and gives me the status (checked = true/false) of checkbox which is clicked.

I am maintaining an object which keeps the track on all the selected checkboxes

var selectedMap  = {};

if( == true){
    var key =;
    var val =;
    selectedMap[key] = val;

and I want to remove the element from the map which is unselected

else if( == false){

when I run this it gives me error in Firebug : selectedMap.remove is not a function

So my question is How can I remove the element when the checkbox is unselected ?



Using delete:

delete selectedMap[];

You're setting the value incorrectly, though. Here's the correct way:

if( == true){
    var key =;   // <== No quotes
    var val =; // <== Here either
    selectedMap[key] = val;

In fact, you could:

if( == true){
    selectedMap[] =;

Getting the event target stuff out of the way, it's easier to envision this with simple strings:

var obj = {}; = "value of foo";
alert(;    // alerts "value of foo" without the quotes
alert(obj["foo"]); // ALSO alerts "value of foo" without the quotes, dotted notation with a literal and bracketed notation with a string are equivalent
delete;    // Deletes the `foo` property from the object entirely
delete obj["foo"]; // Also deletes the `foo` property from the object entirely
var x = "foo";
delete obj[x];     // ALSO deeltes the `foo` property

When using a plain object like this, I always use a prefix on my keys to avoid issues. (For instance, what would happen if your target element's ID was "toString"? The object already has an [inherited] property called "toString" and things would get Very Weird Very Quickly.)

So for me, I do this:

if( == true){
    selectedMap["prefix" +] =;

...and of course:

delete selectedMap["prefix" +];

What you have is an object and not an array (although an array is an object). You declare an object literal with {} whereas an array literal is declared with [].

You can use delete to remove an object property like so

delete selectedMap[];


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.