How to store a key=> value array in JavaScript ?
Last Updated :
10 Jan, 2025
In JavaScript, storing a key-value array means creating an object where each key is associated with a specific value. This allows you to store and retrieve data using named keys instead of numeric indices, enabling more intuitive access to the stored information.
Here are some common approaches:
Approach 1: Using Objects
Using the Objects approach in JavaScript, key-value pairs are stored in an object where each key is associated with a specific value. Objects are ideal for mapping keys to values and are versatile, handling various data types including numbers, strings, and other objects.
Syntax:
for (let i = 0; i < keys.length; i++) {
// obj = Object
// keys = key array
// values = value array
obj[keys[i]] = values[i];
}
Example: In this example we creates an object by mapping keys from the keys array to values from the values.
javascript
// An array of keys
let keys = [1, 2, 3];
// An array of values
let values = ["GeeksforGeeks", "Computer", "Science"];
// Object created
let obj = {};
// Using loop to insert key-value pairs into the object
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
// Printing object to the console
for (let key of Object.keys(obj)) {
console.log(key + " => " + obj[key]);
}
Output1 => GeeksforGeeks
2 => Computer
3 => Science
Approach 2: Using Map() Method
Using the Map approach in JavaScript, key-value pairs are stored in a Map object, which allows keys of any type (including objects and functions) and maintains the order of insertion. Maps provide efficient methods for adding, retrieving, and iterating over elements.
Syntax:
for (let i = 0; i < keys.length; i++) {
// mp = Map
// keys = key array
// values = value array
map.set(keys[i], values[i]);
}
Example: In this example we creates a Map by associating keys from the keys array with values from the values array.
javascript
// An array of keys
let keys = [5, 2, 3, 6, 10];
// An array of values
let values = ["Geeks", "for", "Geeks", "Course", "Algorithm"];
// Map created
let map = new Map();
// Using loop to insert key-value pairs into the map
for (let i = 0; i < keys.length; i++) {
map.set(keys[i], values[i]);
}
// Printing map contents to the console
for (let key of map.keys()) {
console.log(key + " => " + map.get(key));
}
Output5 => Geeks
2 => for
3 => Geeks
6 => Course
10 => Algorithm
Approach 3: Using reduce() Method
The reduce() method in JavaScript iterates over an array to accumulate key-value pairs into an object. It executes a function on each element, building the object as it processes each key-value pair.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: In this example we use the reduce() method to combine two arrays, keys and values, into an object. It then prints each key-value pair from the object using a for...in loop.
JavaScript
// An array of keys
let keys = [5, 2, 3, 6, 10];
// An array of values
let values = ["Geeks", "for", "Geeks", "Course", "Algorithm"];
// Using reduce to store key-value pairs in an object
let ans = values.reduce((acc, value, i) => {
acc[keys[i]] = value; // Assigning value to corresponding key
return acc;
}, {}); // Initializing accumulator as an empty object
// Printing key-value pairs from the object
for (const key in ans) {
console.log(`${key} => ${ans[key]}`);
}
Output2 => for
3 => Geeks
5 => Geeks
6 => Course
10 => Algorithm
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Similar Reads
How to get the Value by a Key in JavaScript Map?
JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys.Different Approaches to Get the Value by a Key in JavaScript Ma
3 min read
How to Get a List of Array Keys in JavaScript?
Here are the different methods to get a list of associative array keys in JavaScript1. Using JavaScript for each loopIn this method, traverse the entire associative array using a for each loop and display the key elements of the array. javascriptlet a = {Newton: "Gravity",Albert: "Energy",Edison: "B
3 min read
How to get a key in a JavaScript object by its value ?
To get a key in a JavaScript object by its value means finding the key associated with a specific value in an object. Given an object with key-value pairs, you want to identify which key corresponds to a particular value, often for searching or data retrieval.How to get a key in a JavaScript object
4 min read
How to view array of a structure in JavaScript ?
The Javascript arrays are heterogeneous. The structure of the array is the same which is enclosed between two square brackets [ ], and the string should be enclosed between either "double quotes" or 'single quotes'. You can get the structure of by using JSON.stringify() or not, here you will see the
3 min read
How To Convert Map Keys to an Array in JavaScript?
Here are the various methods to convert Map keys to an array in JavaScript1. Using array.from() MethodThe Array.from() method in JavaScript converts Map keys to an array by using 'Array.from(map.keys())'. JavaScriptlet map = new Map().set('GFG', 1).set('Geeks', 2); let a = Array.from(map.keys()); co
2 min read
How to Copy Array by Value in JavaScript ?
There are various methods to copy array by value in JavaScript.1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.Syntax
4 min read
How to Store an Object Inside an Array in JavaScript ?
Storing an object inside an array in JavScript involves placing the object as an element within the array. The array becomes a collection of objects, allowing for convenient organization and manipulation of multiple data structures in a single container. Following are the approaches through which it
3 min read
How to Convert Object to Array in JavaScript?
In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
4 min read
How to invert key value in JavaScript object ?
JavaScript is a high-level, interpreted, and dynamically typed client-side scripting language. JavaScript is used to add dynamic features to the static HTML. Everything is an object in JavaScript. Objects in JavaScript can be declared using figure brackets {..} and the objects may comprise certain p
2 min read
How to add Key-Value pair to a JavaScript Object?
A JavaScript object has a key-value pair, and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods.Below are the methods to add a key/value pair to a JavaScript object:Table of ContentUsing Dot NotationUsing Bracket
4 min read