前端,树状结构的两个数组去重,合并


这样子的一个需求,

 

 树状结构的两组数据,要求互斥,并可以搜索,

下面是测试模拟的两组数据

//定义数组

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