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

这样子的一个需求,

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

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

//定义数组

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)

这样的数据处理起来,有点麻烦,我也是请大神前来指教的。。。

扫描二维码关注公众号,回复: 8091253 查看本文章

猜你喜欢

转载自www.cnblogs.com/jiuyueBlog/p/11994235.html
今日推荐