在 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" } ]
广告