Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove property by value from object

Tags:

javascript

I have a simple object like this:

var obj = {
    "option1": "item1",
    "option2": "item2",
    "option3": "item3"
};

For adding a new property to the object I'm using the following code:

obj[this.value] = this.innerHTML;

// this.innerHTML is used just because I'm adding the value I get from a DOM element

Is there a function that can help me remove a property from the object, that receives as a parameter the value of the key-value pair?

For example removeItem('item3');.

like image 753
GVillani82 Avatar asked Jun 16 '13 14:06

GVillani82


1 Answers

That would probably be delete :

delete obj['option1'];

FIDDLE

To do it by value, you'd do something like :

function deleteByVal(val) {
    for (var key in obj) {
        if (obj[key] == val) delete obj[key];
    }
}

deleteByVal('item1');

FIDDLE

like image 179
adeneo Avatar answered Sep 30 '22 10:09

adeneo