前端,樹狀結構的兩個數組去重,合並


這樣子的一個需求,

 

 樹狀結構的兩組數據,要求互斥,並可以搜索,

下面是測試模擬的兩組數據

//定義數組

const arr1 = [{ id: 1, name: [{ name: 'zhang' }] }, { id: 2, name: [{ name: 'wang' }] }]
const arr2 = [{ id: 1, name: [{ name: 'hehe' }, { name: 'zhang' }] }, { id: 3, name: [{ name: 'hah' }] }]

//要求兩組數據合並而且去重
const arr = [...arr1, ...arr2]
const newArr = []
const json = {}
console.log(arr)


arr.map(res => {
if (!json[res.id]) {
json[res.id] = 1
newArr.push(res)
} else {
newArr.map(sub => {
if (sub.id === res.id) {
sub.name = [...sub.name, ...res.name]
}
})
}
})


newArr.map(res => {
res.name = [...new Set(res.name.map(sub => {
return JSON.stringify(sub)
}))].map(res => {
return JSON.parse(res)
})
})
console.log(newArr)

 

這樣的數據處理起來,有點麻煩,我也是請大神前來指教的。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM