How to store two arrays as a keyvalue pair in one object in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have two arrays of literals of same length like these −

const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed'];
const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false];

We are required to write a JavaScript function that takes in two such arrays.

The function should construct an object mapping the elements of the second array to the corresponding elements of the first array.

We will use the Array.prototype.reduce() method to iterate over the arrays, building the object.

Example

The code for this will be −

const arr1 = ['firstName', 'lastName', 'age', 'address', 'isEmployed'];
const arr2 = ['Rahul', 'Sharma', 23, 'Tilak Nagar', false];
const mapArrays = (arr1 = [], arr2 = []) => {
   const res = arr1.reduce((acc,elem,index) =>{
      acc[elem]=arr2[index];
      return acc;
   },{});
   return res;
};
console.log(mapArrays(arr1, arr2));

Output

And the output in the console will be −

{
   firstName: 'Rahul',
   lastName: 'Sharma',
   age: 23,
   address: 'Tilak Nagar',
   isEmployed: false
}
raja
Updated on 23-Nov-2020 11:26:07

Advertisements