在JavaScript中合并两个不同的数组

假设我们有两个数组,第一个数组包含某些事件的预定日期,第二个数组包含这些事件的名称,如下所示:

const dates = [
   {
      id:"1",
      date:"2017-11-07"
   },
   {
      id:"1",
      date:"2017-11-08"
   },
   {
      id:"2",
      date:"2017-11-07"
   },
   {
      id:"2",
      date:"2017-11-08"
   }
];
const names = [
   {
      id:"1",
      name:"Pervies, Peter"
   },
   {
      id:"2",
      name:"Ming, Edmund"
   }
];

我们需要编写一个JavaScript函数,该函数接受两个这样的数组,并根据id属性将事件名称及其对应的日期组合在一起。

因此,对于这些数组,输出应类似于-

const output = [
   {
      id:"1",
      name:"Pervies, Peter",
      details:[
         {date:"2017-11-07"},
         {date:"2017-11-08"}
      ]
   },
   {
      id:"2",
      name:"Ming, Edmund",
      details:[
         {date:"2017-11-07"},
         {date:"2017-11-08"}
      ]
   }
]

示例

为此的代码将是-

const dates = [
   {
      id:"1",
      date:"2017-11-07"
   },
   {
      id:"1",
      date:"2017-11-08"
   },
   {
      id:"2",
      date:"2017-11-07"
   },
   {
      id:"2",
      date:"2017-11-08"
   }
];
const names = [
   {
      id:"1",
      name:"Pervies, Peter"
   },
   {
      id:"2",
      name:"Ming, Edmund"
   }
];
const combineArrays = (dates, names) => {
   const res = [];
   dates.forEach(el => {
      const bool = !res.some(item => {
         return item.id == el.id;
      });
      if(bool){
         let combined = {};
         combined.id = el.id;
         combined.details = combined.details || [];
         combined.details.push({
            "date": el.date
         });
         res.push(combined);
      }else{
         res.find(item => {
            return item.id === el.id;
         })
         .details.push({
            "date": el.date
         });
      };
   });
   res.forEach(el => {
      const bool = names.some(item => {
         return item.id === el.id;
      });
      if(bool){
         el.name = names.find(name => {
            return name.id === el.id;
         }).name;
      };
   });
   return res;
};
console.log(JSON.stringify(combineArrays(dates, names), undefined, 4));

输出结果

控制台中的输出-

[
   {
      "id": "1",
      "details": [
         {
            "date": "2017-11-07"
         },
         {
            "date": "2017-11-08"
         }
      ],
      "name": "Pervies, Peter"
   },
   {
      "id": "2",
      "details": [
         {
            "date": "2017-11-07"
         },
         {
            "date": "2017-11-08"
         }
      ],
      "name": "Ming, Edmund"
   }
]