Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  126] [ 7]  / answers: 1 / hits: 59382  / 10 Years ago, tue, december 16, 2014, 12:00:00

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?


More From » hashmap

 Answers
75

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])
}

[#68467] Saturday, December 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;