使用了两个for循环,为了方便理解,可以理解为父亲找儿子,把儿子写入家族谱
// pid:父id,为0是最顶级数据,其他则对应每项的id,即父.id = 子.pid,则父.children = 子
interface Tree {
id: number
pid: number
name: string
}
let data: Tree[] = [ { id: 1, pid: 0, name: '广东省' }, { id: 2, pid: 0, name: '上海市' }, { id: 3, pid: 0, name: '福建省' }, { id: 4, pid: 1, name: '深圳市' }, { id: 5, pid: 1, name: '珠海市' }, { id: 6, pid: 2, name: '上海市' }, { id: 7, pid: 3, name: '厦门市' }, { id: 8, pid: 1, name: '广州市' }, { id: 9, pid: 8, name: '天河区' }, { id: 10, pid: 4, name: '南山区' }, { id: 11, pid: 4, name: '福田区' } ] /** * 处理树状数据函数 * @param data 原始树状数据 * @return 处理后的树状数据 */ function getTrees(data: Tree[]) { // 父亲找儿子,把儿子写入家族谱 data.forEach((v, i, arr) => { // v:儿子 arr.forEach((v1: any, y) => { // v1:父亲 if (v1.id == v.pid) { // 父亲找到儿子了,就添加到children if (!v1.children) v1.children = [] v1.children.push(v) } }) }) return data } let newTrees = getTrees(trees) let newArr = newTrees.filter((v) => v.pid == 0) console.log(newArr)
标签:children,name,树状,pid,js,v1,数据处理,data,id From: https://www.cnblogs.com/jinbang/p/17136836.html