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?
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])
}
hash["dynamic"] = 5
will insert something. Object.keys(hash).length
will get the size.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With