Computer >> Máy Tính >  >> Lập trình >> Javascript

Kết hợp hai mảng khác nhau trong JavaScript

Giả sử chúng ta có hai mảng, mảng đầu tiên chứa ngày đã lên lịch cho một số sự kiện và mảng thứ hai chứa tên của những sự kiện đó, như thế này -

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"
   }
];

Chúng tôi bắt buộc phải viết một hàm JavaScript có hai mảng như vậy và kết hợp tên của chúng với ngày tháng tương ứng của chúng dựa trên thuộc tính id.

Do đó, đối với các mảng này, đầu ra sẽ giống như -

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"}
      ]
   }
]

Ví dụ

Mã cho điều này sẽ là -

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

Đầu ra

Đầu ra trong bảng điều khiển -

[
   {
      "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"
   }
]