Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 547
user1817439 Avatar asked Dec 16 '14 18:12

user1817439


4 Answers

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])
}
like image 91
juvian Avatar answered Sep 25 '22 00:09

juvian


hash["dynamic"] = 5 will insert something. Object.keys(hash).length will get the size.

like image 34
b4hand Avatar answered Sep 22 '22 00:09

b4hand


Please see this guide on JavaScript Objects: http://www.w3schools.com/js/js_objects.asp

JavaScript objects can be accessed in a number of ways. Let's take this object as an example:

var person = {
  first_name: "John",
  last_name: "Smith",
  age: 39
};

If you wished to access the first_name you could do:

person.first_name;

Or

person['first_name'];

These would both retrieve the value.

You may also set the value in similar fashion:

person.first_name = "Michael";

Now, if you were referring to creating an iterator using a keys() method like in Java then you can't do that exactly, but you can do something similar.

You can iterate over the object however in a similar manner that you would iterate over an array:

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // do stuff
  }

}

A newer built-in is also available where you can use Object.keys(person) to get an array of the objects keys. Read more here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

I suggest using Google a little more. There are plenty of resources out there for this type of question. You would find the answer more quickly than someone would respond on here.

like image 36
Michael Garner Avatar answered Sep 23 '22 00:09

Michael Garner


You can use the built-in Map object.

var myMap = new Map();
var keyObj = {};
myMap.set(keyObj, "value");
myMap.get(keyObj); 

for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}

More information here : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Map

like image 25
user9269553 Avatar answered Sep 22 '22 00:09

user9269553