0

I am creating the map as follows:

    var employeeMap = new Object();
   addElement(employeeMap , 1, "ABC");
   addElement(employeeMap , 2, "ABCD");

    alert(getElement(employeeMap,1)); // ABC

    function addElement(map,key,value){
        map[key] = value;
        return map;
    }

    function getElement(map,key){
        return map[key];
    }

How to delete a key-value pair from the map ? Is setting the map[key] = null the only option ?

Thanks, Shikha

2 Answers 2

1

To actually remove the key/value pair, use delete: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete

So you could create a function to remove elements:

function deleteElement(map, key)) {
    if (map.hasOwnProperty(key) {
        delete map[key];
    }
}

And call it like:

deleteElement(employeeMap, 2);

UPDATE:

But as I'm reading, delete returns true if it's successful, and false only if it cannot be deleted (for several reasons). So i guess the real version would be what the other answer has:

function deleteElement(map, key)) {
    return (delete map[key]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can skip the hasOwnProperty test since delete won't remove properties from the prototype chain.
@thesystem Yeah, I started reading more of the MDN docs and realized that...was editing as you commented. Thanks!
0

Use delete:

delete employeeMap[1]

To follow the pattern of your functions:

function deleteElement(map,key){
    return delete map[key];
}

deleteElement(employeeMap, 1);

Comments

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.