Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to create an object from two arrays in JavaScript?

  • Last Updated : 31 Mar, 2021

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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: Using for-each loop.



Javascript




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))


Output:

{
  1: "ram",
  2: "shyam",
  3: "sita",
  4: "gita"
}

Example 2: Using Object.assign method.

Javascript




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))


Output:

{
  1: "ram",
  2: "shyam",
  3: "sita",
  4: "gita"
}



My Personal Notes arrow_drop_up
Recommended Articles
Page :