实现 JSON.stringify(val, replacer, space)
JSON.stringify(val, replacer, space)
function format(val, replacer, space) { // TODO var fn = (data, spaceIn) =>{ let type = Object.prototype.toString.call(data) if(type == '[object Number]'){ return data+'' }else if(type == '[object String]'){ return data }else if(type == '[object Array]'){ let res = '' for(let arr of data){ res += (res?',':'')+'\n'+' '.repeat(spaceIn)+fn(arr, spaceIn+space) } return '['+res+'\n'+' '.repeat(spaceIn)+']' }else if(type == '[object Object]'){ let res = '' for(let [key, value] of Object.entries(data)){ res += '\n'+' '.repeat(spaceIn)+key+':'+fn(value, spaceIn+space) + ',' } if(res[res.length-1] == ','){ res = res.slice(0,-1) } return '{'+res+'\n'+' '.repeat(spaceIn-space)+ '}' } } return fn(val, space) } var data = [ {id:1,name:'json',parentId:0}, {id:2,name:'json',parentId:0}, {id:3,name:'json',parentId:1}, {id:4,name:'json',parentId:2}, {id:5,name:'json',parentId:3}, {id:6,name:'json',parentId:4}, {id:7,name:'json',parentId:5}, {id:8,name:'json',parentId:5}, {id:9,name:'json',parentId:8}, {id:10,name:'json',parentId:2}, ] var buildTree = (data) => { data.sort((a, b) => a.parentId - b.parentId) while(data[data.length - 1].parentId > 0){ let cur = data.pop() let parent = data.filter((node)=>{ return node.id == cur.parentId }) if(parent.length == 1){ if(typeof(parent[0].children) == 'object'){ parent[0].children.push(cur) }else{ parent[0].children = [] parent[0].children.push(cur) } } } return data } console.log( format( buildTree(data),1,2 ))
改进思路:按层排列结点,然后从叶子到根链接树
var buildTree = (data) => {
let n = data.length
let level = []
level.push(...data.filter((val)=>val.parentId == 0))
for(let i = 0;i<n;i++){
let children = data.filter((val)=>val.parentId == level[i].id)
for(let child of children){
level.push(child)
}
}
while(level[level.length - 1].parentId > 0){
let cur = level.pop()
let parent = level.filter((node)=>{
return node.id == cur.parentId
})
if(parent.length == 1){
if(typeof(parent[0].children) == 'object'){
parent[0].children.push(cur)
}else{
parent[0].children = []
parent[0].children.push(cur)
}
}
}
return level
}