JavaScript: Obtain key-value pairs in an array
In this article let us understand what a “key” and a “value” is in an array is & also look at the different methods by which we can obtain these key-value pairsTable of Contents
- What are a key and value in an array?
- Different methods to obtain key-value pairs
- Browser Support
- Other Related Concepts
What are a key and value in an array?
Keys are indexes and values are elements of an associative array. Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loopHere’s an example of an associative array
var arr = { "one": 1, "two": 2, "three": 3 };
Unlike simple arrays, we use curly braces instead of square brackets. The content or values of associative arrays is accessed by keys.In the above array, one, two & three are keys, and 1, 2 & 3 are values. These can be obtained individually using the keys() & values() methods as shown below
//to get values
for (let value of Object.values(arr)) {
alert(value);
}
//Output: 1, 2, 3
//to get keys
for (let value of Object.values(arr)) {
alert(value);
}
//Output: one, two, three
Different methods to obtain key-value pairs
Now that we know how to get keys & values in an array, let us look at the different methods to obtain key-value pairs.Let us first store the previously extracted keys & values in separate arrays
var keys = ["one", "two", "three"];
var values = [1, 2, 3];
Method 1: Using an object to store key => value pairs
In this method we store the elements from the “keys” array & the corresponding values from the “values” array using an associative array "obj"// create object
var obj = {};
// Loop to insert key & value in this object one by one
for (var i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
// output can be displayed as : one => 1 two => 2 three => 3
Method 2: Using the map() method
A map is a collection of elements where each element is stored as a key, value pair. The objects of map type can hold both objects and primitive values as either key or value. On traversing through the map object, it returns the key, value pair in the same order as inserted.// Create a map object
var map = new Map();
// Loop to insert key & value in this object one by one
for(var i = 0; i < keys.length; i++){
map.set(keys[i], values[i]);
}
// output can be displayed as : one => 1 two => 2 three => 3