如何将数组与值为数组的对象合并 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 17:16:17

假设我们有一个数组和一个像这样的对象 −

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

我们需要压缩数组和对象,以便将数组中的值分配给以对象中的值作为键的新对象。

像这样 −

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

我们将迭代每个数组项并同时为新对象的键分配值。

示例

以下是代码 −

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

输出

这将在控制台中产生以下输出 −

{
   group1: { Ram: 1, Mohan: 2, Shyam: 3 },
   group2: { Jai: 4, Dinesh: 5 }
}

相关文章


有用资源