How to merge an array with an object where values are arrays - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array and an object like these −

const arr = [1, 2, 3, 4, 5];
const obj = {
   group1: ["Ram", "Mohan", "Shyam"],
   group2: ["Jai", "Dinesh"],
};

We are required to zip the array and the object so that the values in the array are assigned to the new objects that are keyed with the values in the object.

Like this −

const output = {
   group1: {
       "Ram": 1,
       "Mohan": 2,
       "Shyam": 3
   },
   group2: {
       "Jai": 4,
       "Dinesh": 5
   }
};

We will iterate over each array item and simultaneously assign values to the new object’s keys.

Example

Following is the code −

const arr = [1, 2, 3, 4, 5];
const obj = {
   group1: ["Ram", "Mohan", "Shyam"],
   group2: ["Jai", "Dinesh"],
};
const zipObject = (arr, obj) => {
   const res = {};
   for(let i = 0; i < arr.length; i++){
      if(obj['group1'][i]){
         if(!res['group1']){
            res['group1'] = {};
         };
         res['group1'][obj['group1'][i]] = arr[i];
      }else{
         if(!res['group2']){
            res['group2'] = {};
         }
         res['group2'][obj['group2'][i - obj['group1'].length]] =
         arr[i];
      };
   };
   return res;
};
console.log(zipObject(arr, obj));

Output

This will produce the following output in console −

{
   group1: { Ram: 1, Mohan: 2, Shyam: 3 },
   group2: { Jai: 4, Dinesh: 5 }
}
raja
Published on 18-Sep-2020 16:31:45
Advertisements