How to create an object from the given key-value pairs using JavaScript ?
Last Updated :
12 Aug, 2024
In this article, we will learn to create an object from the given key-value pairs using JavaScript.Key-value pair: Unique identifier (key) associated with its corresponding value; fundamental for data organization and retrieval in programming. here we have some common approaches.
We will explore the process of creating objects from key-value pairs in JavaScript. Key-value pairs are fundamental in organizing and retrieving data efficiently within programs. We’ll discuss various common approaches to achieve this goal, empowering you with the knowledge to handle key-value data effectively in your JavaScript projects. Let’s see and discover these approaches together.
Following are some approaches to achieve the mentioned target.
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using Numerical Keys and Values in JavaScript
In this approach initializes an empty object and adds key-value pairs using numerical keys, resulting in an object with properties assigned to respective values.
Example 1: This is the simplest as well as the native approach. In this approach, we will directly append the key-value pair(s) in that previously created empty object.
JavaScript
let object = {};
let firstKey = 0;
let firstKeyValue = "GeeksforGeeks";
let secondKey = 1;
let secondKeyValue = "Hello JavaScript";
let thirdKey = 2;
let thirdKeyValue = "Hello React";
object[firstKey] = firstKeyValue;
object[secondKey] = secondKeyValue;
object[thirdKey] = thirdKeyValue;
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Approach 2: Using Object.assign()
In this approach uses Object.assign() to add key-value pairs with numerical keys to an empty object, creating an object with properties assigned to corresponding values.
Example: In this example, we will use Object.assign() method which is the part of the Object superclass. This method will copy all the values and will append those values in the object as key-value pair(s).
JavaScript
let object = {};
let firstKey = 0;
let firstKeyValue = "GeeksforGeeks";
let secondKey = 1;
let secondKeyValue = "Hello JavaScript";
let thirdKey = 2;
let thirdKeyValue = "Hello React";
Object.assign(object, { [firstKey]: firstKeyValue });
Object.assign(object, { [secondKey]: secondKeyValue });
Object.assign(object, { [thirdKey]: thirdKeyValue });
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Approach 3: Using for loop
In this approach we are using for loop to create an object by iterating over two arrays containing keys and values, assigning properties to the object accordingly.
Example: In this example, we will consider that our keys and their corresponding values are present in an array. We will first run a for loop over the array, and then we will dynamically append our data from the arrays into an empty object as key-value pair(s).
JavaScript
let object = {};
let keys = [0, 1, 2];
let values = ["GeeksforGeeks",
"Hello JavaScript", "Hello React"];
for (let i = 0; i < keys.length; i++) {
object[keys[i]] = values[i];
}
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Output:
{ "0": "GeeksforGeeks", "1": "Hello JavaScript", "2": "Hello React" }
Approach 4: Using a custom function
The approach involves a custom function that takes arrays of keys and values as arguments. It iterates through the arrays, assigning properties to the object with corresponding keys and values.
Example: The example uses a custom function to create an object with numerical keys and corresponding string values from arrays.
JavaScript
function createObject(keys, values) {
const object = {};
for (let i = 0; i < keys.length; i++) {
object[keys[i]] = values[i];
}
return object;
}
const keys = [0, 1, 2];
const values =
["GeeksforGeeks", "Hello JavaScript", "Hello React"];
const object = createObject(keys, values);
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Approach 5: Using the Map object
In this approach we are using the Map object and the Object.fromEntries() method to create an object from arrays of keys and values, effectively mapping numerical keys to their corresponding string values.
Example: The example uses the Map object and Object.fromEntries() to create an object with numerical keys and string values from arrays.
JavaScript
const keys = [0, 1, 2];
const values = ["GeeksforGeeks", "Hello JavaScript", "Hello React"];
const keyValuePairs = keys.map((key, index) => [key, values[index]]);
const object = Object.fromEntries(keyValuePairs);
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Approach 6: Using Array.prototype.reduce()
In this approach, we utilize the reduce method on arrays of keys and values to build an object. The reduce method iterates through the arrays, adding each key-value pair to the accumulator object.
Syntax:
let object = keys.reduce((acc, key, index) => {
acc[key] = values[index];
return acc;
}, {});
Example: This example demonstrates how to use the reduce method to create an object from arrays of keys and values.
JavaScript
const keys = [0, 1, 2];
const values = ["GeeksforGeeks", "Hello JavaScript", "Hello React"];
const object = keys.reduce((acc, key, index) => {
acc[key] = values[index];
return acc;
}, {});
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Approach 7: Using Object.fromEntries with zip Method
Another approach to creating an object from key-value pairs in JavaScript is by combining the Object.fromEntries() method with a custom zip function. This approach is useful when you want to pair elements from two arrays (one for keys and one for values) and then convert them directly into an object.
Example:
JavaScript
function zip(arr1, arr2) {
return arr1.map((key, index) => [key, arr2[index]]);
}
const keys = [0, 1, 2];
const values = ["GeeksforGeeks", "Hello JavaScript", "Hello React"];
const object = Object.fromEntries(zip(keys, values));
console.log(object);
Output{ '0': 'GeeksforGeeks', '1': 'Hello JavaScript', '2': 'Hello React' }
Similar Reads
How to add Key-Value pair to a JavaScript Object?
JavaScript object has 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 Content Using Dot NotationUsing Bracket No
3 min read
How to convert an Object {} to an Array [] of key-value pairs in JavaScript?
Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). Methods to convert the Objects to JavaScript Array: 1. Using Obj
3 min read
How to Create an HTML Table from an Object Array Using JavaScript ?
Tables are a fundamental part of web development, and displaying data in a structured manner is a common requirement. JavaScript provides a powerful way to dynamically generate HTML content, making it easy to create tables from object arrays. Table of Content Using innerHTML propertyUsing appendChil
2 min read
How to get Values from Specific Objects an Array in JavaScript ?
In JavaScript, an array is a data structure that can hold a collection of values, which can be of any data type, including numbers, strings, and objects. When an array contains objects, it is called an array of objects. Table of Content Using the forEach() methodUsing the map() methodUsing the filte
2 min read
How to swap key and value of JSON element using JavaScript ?
In this article, we will swap the key and value of JSON elements using JavaScript. Given a JSON object and the task is to swap the JSON object key with values and vice-versa with the help of JavaScript. Below are the following approaches: Using for loopUsing Object.keys() and ForEach() MethodUsing O
2 min read
How to convert Object's array to an array using JavaScript ?
Given an array of objects and the task is to convert the object values to an array with the help of JavaScript. There are two approaches that are discussed below: Approach 1: We can use the map() method and return the values of each object which makes the array. Example: [GFGTABS] html <!DOCTYPE
2 min read
How to unflatten an object with the paths for keys in JavaScript ?
In this article, we will learn to unflatten an object which has a certain number of key-value pairs(s) within it with the paths for the keys in JavaScript. Problem Statement: You are given an object with several key-value pair(s). Some keys have various keys names present after a dot, you basically
4 min read
How to Create Dynamic Values and Objects in JavaScript?
In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and
3 min read
How to create a Number object using JavaScript ?
In this article, we will discuss how to create a Number object using JavaScript. A number object is used to represent integers, decimal or float point numbers, and many more. The primitive wrapper object Number is used to represent and handle numbers. examples: 20, 0.25. We generally don't need to w
2 min read
How to add a property to a JavaScript object using a variable as the name?
In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability. There are several methods that can be used to add a property to a JavaScript objec
2 min read