let source = [
{
id: 1,
pid: 0,
name: 'body'
},
{
id: 2,
pid: 1,
name: 'title'
},
{
id: 3,
pid: 2,
name: 'div'
}
]
function jsonToTree(data) {
let parents = data.filter(p => p.pid === 0),
children = data.filter(c => c.pid !== 0);
formatData(parents,children)
function formatData(parents,children) {
parents.map(p => {
children.map((c, index) => {
if (p.id == c.pid) {
let _c = JSON.parse(JSON.stringify(children))
_c.splice(index, 1)
formatData([c],_c)
if(p.children){
p.children.push(c)
}else{
p.children = [c]
}
}
})
})
}
return parents
}
function mapToTree(data){
let map = {}
let result = []
data.forEach(item => map[item.id] = item)
data.forEach(item =>{
let parent = map[item.pid]
if(parent){
if(parent.children){
parent.children.push(item)
}else{
parent.children = [item]
}
}else{
result.push(item)
}
})
return result
}
console.log('map',mapToTree(source))