12

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

3
  • 1
    The built-in delete keyword? Commented Jun 16, 2013 at 14:37
  • 3
    Can I refer to value insted of the key? Commented Jun 16, 2013 at 14:39
  • Not natively, you would have to write your own function that would iterate through all of the object's properties looking for your desired value, and delete the property(-ies) whose value match the value you're looking for. Commented Jun 16, 2013 at 14:40

3 Answers 3

18

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

Sign up to request clarification or add additional context in comments.

3 Comments

Can I remove the element that has value equal to item1 ?
@Joseph82 Note that the function above will delete multiple properties with the same value. Also, it loosely checks type with == as opposed to ===. None of this is bad or wrong, it just depends upon what you want/need.
Ok. I'm sure my values are all different.
2

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 i.e mutate anything in its outer environment and does not depend on any global variable for its operation.

Comments

-1

Like this-

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

1 Comment

You misinterpreted the question. The question asks how to delete key/value pairs selecting by VALUE, not by key. Please consider deleting or editing your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.