Search code examples
javascripthashmapkeyvaluepair

Is there a way to create hashmap in javascript and manipulate it like adding and deleting values


My requirement is to store key-value pairs in a data structure and fetch or delete the pairs when necessary using keys in JavaScript.

How can I do it in JavaScript as one does it in Java?

I have seen an answer creating an instance of hash map like:

var hash={};

Now Ie can add values in it like:

hash={ "January":"1","Feb":"2" }

Can I insert values dynamically using keys and fetch them and also get the size of the hash map?


Solution

  • Yes, that's an associative array (var hash = new Object();)

    //You can add in these ways:
    
    hash.January='1';
    hash['Feb']='2';
    
    //For length:
    console.log(Object.keys(hash).length)
    
    //To fetch by key:
    console.log(hash['Feb']) // '2'
    
    //To fetch all:
    for(var key in hash){
        console.log('key is :' + key + ' and value is : '+ hash[key])
    }