简体   繁体   中英

Remove property by value from object

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

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

This question has been answered correctly but there is just one thing I want to add:

You should write a pure function for this solution. That is a function that does not require your object to be defined in the global scope.

so:

const deleteObjectItemByValue = (Obj, val) => {
    for (var key in Obj) {
        if (Obj[key] == val) {
            delete Obj[key];
            return Obj;
        }
    }
};

usage: deleteObjectItemByValue(yourObj, val); This is a pure function that does not have side effects ie mutate anything in its outer environment and does not depend on any global variable for its operation.

Like this-

delete obj["option1"]; Or delete obj.option1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM