這樣子的一個需求,
樹狀結構的兩組數據,要求互斥,並可以搜索,
下面是測試模擬的兩組數據
//定義數組
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)
這樣的數據處理起來,有點麻煩,我也是請大神前來指教的。。。