The Keys and values method in Javascript

Web DevelopmentFront End TechnologyJavascript

Sometimes when working with a dictionary, we need only the keys of the dictionary as an array for some task. We can easily get the properties of an object using Object.keys. We'll use this method to return the keys from our container object. 

Example

keys() {
   return Object.keys(this.container);
}

You can test this using − 

Example

const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

console.log(myMap.keys());

Output

This will give the output −

[ 'key1', 'key2' ]

In ES6 Map, the same method is available that you can use. Note that it returns a MapIterator object, which you can convert to an array or use like a normal iterator. For example, 

Example

const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);

console.log(myMap.keys())

Output

This will give the output −

MapIterator { 'key1', 'key2' }

Similarly, there are cases when only values of the dictionary are required. For such cases, we need to loop through the dictionary and collect the values. For example, 

Example

values() {
   let values = [];
   for (let key in this.container) {
      values.push(this.container[key]);
   }
   return values;
}

You can test these methods using − 

Example

const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
console.log(myMap.values());

Output

This will give the output −

[ 'value1', 'value2' ]

Again in ES6 Map, this is available just like the keys method and can be used like it.

raja
Published on 27-Jun-2018 13:59:57
Advertisements