The Keys and values method in Javascript


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.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements