The keys function of a JavaScript Map produces a new Map iterator object. This object holds the keys corresponding to each entry within the Map. It preserves the order in which the elements were inserted.
Syntax
The syntax for the keys method is expressed as follows:
map.keys;
Parameters:
keys: This method does not require any arguments. In JavaScript, the keys function yields a Map Iterator object. We can employ the for…of loop to sequentially retrieve each key.
Return Value:
It yields a fresh iterable iterator object specifically for the Map.
JavaScript map.keys method examples
In this section, we will explore the keys method by examining a range of examples.
Example 1: Applying map.keys method
Let's see a simple example of the keys method.
Example
var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
var itr=map.keys();
console.log(itr.next().value);
console.log(itr.next().value);
console.log(itr.next().value);
Output:
1
2
3
Explanation:
In the preceding example, we established a variable called map using the var keyword and assigned it a new Map constructor, which instantiates a new Map object. We then inserted three entries into this map. Additionally, we declared another variable named itr, again utilizing the var keyword, and assigned it the result of map.keys, which generates an iterator for the keys contained within the map. This method produces an iterator object that sequentially yields each key according to the order of insertion. By invoking itr.next, we retrieve the next element from the iterator, and using .value, we access the key provided by the iterator. The result is then logged to the console, resulting in an output of 1 2 3.
Example 2: Example of map.keys utilizing a for loop
Let's see the same example using a for loop .
Example
var map = new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
var itr=map.keys();
for(let i = 0; i<map.size; i++)
{
console.log(itr.next().value);
}
Output:
1
2
3
Explanation:
In this illustration, we established a variable called map using the var keyword, and initialized it with a new Map to create a fresh Map object. Subsequently, we incorporated three entries into the map. Additionally, we set up another variable named itr with the var keyword and assigned it the result of map.keys, which provides an iterator for the keys 1, 2, and 3. The expression map.size reveals the total count of entries within the map, which is 3. A for loop is employed to execute three iterations. During each cycle, itr.next.value retrieves the subsequent key from the iterator and outputs the result to the console, resulting in the display of 1, 2, 3.
Example 3: Example of utilizing objects as keys
Let's examine an illustration of employing objects as keys.
Example
const obj1 = { id: 1 };
const obj2 = { id: 2 };
const map = new Map();
map.set(obj1, "Object 1");
map.set(obj2, "Object 2");
for (let key of map.keys()) {
console.log(key); // logs the object references
}
Output:
{ id: 1 }
{ id: 2 }
Explanation:
In this instance, we define a variable called map using the const declaration and initialize it with a new Map which generates a fresh Map object. We have stored the two objects, obj1 and obj2, as keys in the map, associating them with designated string values. Next, we will traverse through all the keys in the map by employing map.keys.
The map.keys method provides an iterator that traverses the keys of both obj1 and obj2. The for…of loop then goes through these keys, printing the results, resulting in the output { id: 1 } { id: 2 }.
Example 4: Example of converting keys to an array
In this illustration, we will transform the keys into an array format.
Example
const map = new Map([
["x", 10],
["y", 20],
]);
const keyArray = Array.from(map.keys());
console.log(keyArray); // ["x", "y"]
Output:
[ 'x', 'y' ]
Explanation:
In this illustration, we establish a variable called map using the const keyword and assign it a new instance of Map which generates a new Map object. Within this newly created map, we inserted two entries: ["x", 10] and ["y", 20]. Next, we declare another variable referred to as keyArray, also using the const keyword, and assign it the value of Array.from(map.keys), which provides an iterator that enumerates the keys within the map. Here, the keys are x and y. The Array.from(...) method takes this iterator and transforms it into a standard array, which is then logged to the console, resulting in the output [ 'x', 'y' ].
Conclusion:
In JavaScript, the Map.keys method offers a straightforward and effective approach to obtain all the keys from a Map object. This method yields a new Iterator object that presents the keys in the sequence they were added, enabling us to traverse them using for...of loops, the spread operator, or various other iteration techniques.
The Map.keys method serves a specific purpose in JavaScript. It retrieves an iterable object that contains the keys of a Map instance in the order they were added. This functionality is particularly useful when you need to access only the keys from a Map without the associated values.
Here’s a concise breakdown of its utility:
- Return Type: The method returns a new Iterator object, which allows iteration over the keys of the Map.
- Order Preservation: The keys are yielded in the same sequence as they were inserted into the Map, maintaining the insertion order.
- Usage in Loops: It is commonly employed in loops, such as for...of, to iterate through the keys efficiently.
For instance, consider the following example illustrating the Map.keys method in action:
const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 30);
myMap.set('occupation', 'Engineer');
for (const key of myMap.keys()) {
console.log(key);
}
In this example, the output will display:
name
age
occupation
Each key is printed in the order it was added to the Map. The Map.keys method is an essential tool for developers needing to work with key data in a Map structure.
The Map.keys function generates a fresh iterator object that presents the keys of a Map in the order they were added. This iterator can be employed to iterate through the keys or be transformed into an array. It exclusively yields the keys, leaving out the corresponding values, and does not alter the original Map in any way.
- What is the sequence in which the keys are returned?
Keys are retrieved in the sequence in which they were added. This sequence of insertion is maintained in a Map, meaning that even if the associated values are modified, their respective order remains unchanged. This characteristic distinguishes Maps from standard objects, providing a consistent and dependable iteration process.
- What is the method to transform map.keys into an array?
We can employ the spread operator [...map.keys] or use Array.from(map.keys) to transform map.keys into an array. Both methods will yield an array containing the keys.
- What kinds of keys are permissible in a Map?
In a Map, keys can be of any data type. This includes strings, numbers, objects, functions, or even NaN. The method Map.keys retrieves all keys in their proper sequence. The keys of objects within a Map are compared based on their reference. This versatility is a significant advantage of employing a Map.
- Do duplicate keys appear in Map.keys?
No, a Map does not permit the inclusion of duplicate keys. If an attempt is made to add a key that already exists, it will overwrite the existing value. Consequently, the output of Map.keys will only display distinct keys. The order of these keys corresponds to their initial insertion, unless they have been replaced. It functions similarly to a collection of unique keys.
- Is it possible to convert Map.keys into JSON?
Not in a direct manner, as iterators cannot be serialized into JSON format. To transform it into JSON, we must first convert the iterator into an array by employing the spread operator ([...map.keys]) or by using Array.from(map.keys).