How to create an object from two arrays in JavaScript?
Given two arrays the task is to create an object from them where the first array contains the keys of the object and the second array contains the values of the object. Return null if the array lengths are not the same or if the arrays are empty. An example of this problem in real life is, for example, you have got an array of roll number of students and an array of the name of the students which are in the same order, and you want to create an object so that you can access the student name using the roll number easily.
Example:
Input: Array 1 => [1, 2, 3, 4] Array 2 => ["ram", "shyam", "sita", "gita"] Output: { 1: "ram", 2: "shyam", 3: "sita", 4: "gita" }
To solve this problem we have the following approaches:
Example 1: In this example, we will be using Javascript`s for-each loop.
Javascript
<script> let a = [1, 2, 3, 4]; let b = [ "ram" , "shyam" , "sita" , "gita" ] // Checking if the array lengths are same // and none of the array is empty function convertToObj(a, b){ if (a.length != b.length || a.length == 0 || b.length == 0){ return null ; } let obj = {}; // Using the foreach method a.forEach((k, i) => {obj[k] = b[i]}) return obj; } console.log(convertToObj(a, b)) </script> |
Output:
{ 1: "ram", 2: "shyam", 3: "sita", 4: "gita" }
Example 2: In this example, we will be using Javascript`s Object.assign method.
Javascript
<script> let a = [1, 2, 3, 4]; let b = [ "ram" , "shyam" , "sita" , "gita" ] // Checking if the array lengths are same // and none of the array is empty function convertToObj(a, b){ if (a.length != b.length || a.length == 0 || b.length == 0){ return null ; } // Using Object.assign method return Object.assign(...a.map((k, i)=>({[k]: b[i]}) )) } console.log(convertToObj(a, b)) </script> |
Output:
{ 1: "ram", 2: "shyam", 3: "sita", 4: "gita" }
Example-3: In this example, we will be using Javascript`s reduce() method.
Javascript
<script> let a = [1, 2, 3, 4]; let b = [ "ram" , "shyam" , "sita" , "gita" ]; // Checking if the array lengths are same // and none of the array is empty function convertToObj(a, b) { if (a.length != b.length || a.length == 0 || b.length == 0) { return null ; } // Using reduce() method let object = a.reduce((acc, element, index) => { return { ...acc, [element]: b[index], }; }, {}); return object; } console.log(convertToObj(a, b)); </script> |
Output: Here in output we will experience the keys of an object in string format by default.
{ '1': 'ram', '2': 'shyam', '3': 'sita', '4': 'gita' }
Please Login to comment...