合並多維數組,網上有挺多例子,可惜都不是我需求的模樣,於是自己花了點時間整理了一下出來
思路比較清晰,看到多維,想到的方法便是降維,於是,利用了對象鍵值對的關系用來做判斷
直接上代碼了:例子只考慮了兩個列表都有數據的情況,其他情況就加一下簡單判斷就行了
let arr1=[ { name:"測試1", list:[ { id:"1", content:{} }, { id:"2", content:{} }, { id:"3", content:{} } ] }, { name:"測試2", list:[ { id:"4", content:{} }, { id:"5", content:{} } ] } ] let arr2=[ { name:"測試1", list:[ { id:"1", content:{} }, { id:"5", content:{} } ] }, { name:"測試4", list:[ { id:"6", content:{} }, { id:"7", content:{} } ] } ] //臨時數組,用來存儲合並后的內容 let resultList = []; //隱藏對象,用來判斷name是否存在 let cacheObject = {}; //合並兩個數組 let newList = arr1.concat(JSON.parse(arr2)); newList.forEach(item => { //判斷對象中是否存在對應建 if (!cacheObject[item.name]) { //如果不存在,直接push cacheObject[item.name] = item.list; resultList.push(item); } else { //如果存在,判斷list字段里面是否相同id let pos = Object.keys(cacheObject).findIndex( key => key === item.name ); //與上面臨時數組對象相同(后續有時間可優化為遞歸遍歷) let listItems = []; let cacheIds = {}; item.list .concat(cacheObject[item.name]) .forEach(sitem => { //判斷brandId是否存在 if (!cacheIds[sitem.brandId]) { cacheIds[sitem.brandId] = sitem; listItems.push(sitem); } }); resultList[pos].list = listItems; } });
