const list = [
{ id: 1, name: '西药', parentId: 0 },
{ id: 2, name: '中药', parentId: 0 },
{ id: 3, name: '中成药', parentId: 0 },
{ id: 4, name: '阿莫西林胶囊', parentId: 1 },
{ id: 5, name: '奥美拉唑', parentId: 1 },
{ id: 6, name: '人参', parentId: 2 },
{ id: 7, name: '当归', parentId: 2 },
{ id: 8, name: '祛湿颗粒', parentId: 6 },
{ id: 8, name: '复方甘草片', parentId: 6 }
]
function convert1() {
const tree = []
for (let i = 0, len = list.length; i < len; i++) {
if (list[i].parentId === 0) {
tree.push(list[i])
} else {
for (let j = 0, jlen = tree.length; j < jlen; j++) {
if (list[i].parentId === tree[j].id) {
if (!tree[j].children) {
tree[j].children = [list[i]]
} else {
tree[j].children.push(list[i])
}
}
}
}
}
}
const a = {}
function convert2() {
const tree2 = []
const map = {}
list.forEach(item => {
map[item.id] = item
})
debugger
list.forEach(item => {
if (item.parentId !== 0) {
// map[item.parentId]就会指向map[item.id]
// parentId绑定的就是父级的id
map[item.parentId]['children']
? map[item.parentId]['children'].push(item)
: map[item.parentId]['children'] = [item]
} else {
tree2.push(item)
}
})
// console.log(map)
console.log(tree2)
}
function convert3(list, topId = 0) {
const result = [];
const map = {};
list.forEach(item => {
const { id, parentId } = item;
if (parentId === topId) {
result.push(item);
} else {
map[parentId] = map[parentId] || [];
map[parentId].push(item)
}
item.children = item.children || map[id] || (map[id] = [])
})
return result;
}
// console.log(convert2(list))
const commentlist = [
{
parentId: 0,
id: 1,
comment: '评论1'
},
{
parentId: 1,
id: 2,
comment: '评论1的回复评论'
},
{
parentId: 0,
id: 3,
comment: '评论2'
},
{
parentId: 2,
id: 4,
comment: '评论1的回复的回复'
},
{
parentId: 0,
id: 5,
comment: '评论3'
},
{
parentId: 5,
id: 6,
comment: '评论3的回复'
}
]
function flat3(arr) {
let arrs = [];
arr.forEach(item => {
// console.log(item)
if (Array.isArray(item.children)) {
console.log('cc')
arrs.push(...flat3(item.children))
} else {
arrs.push(item)
}
})
return arrs
}
function cc(list) {
const map = {}
const arr = []
// console.log(list)
list.forEach(item => {
if (item.parentId === 0) {
arr.push(item)
} else {
map[item.parentId] = map[item.parentId] || [];
map[item.parentId].push(item)
}
item.children = item.children || map[item.id] || (map[item.id] = [])
})
arr.forEach(item => {
console.log(item)
item.children = flat3(arr.children)
return item
})
// console.log(arr)
// console.log('map', map)
// console.log('arr', arr)
}
cc(commentlist)
console