js 数组 转为树形结构
生活随笔
收集整理的這篇文章主要介紹了
js 数组 转为树形结构
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目:
source = [{id: 1,pid: 0,name: 'body'}, {id: 2,pid: 1,name: 'title'}, {id: 3,pid: 2,name: 'div'}]轉(zhuǎn)換為: [{id: 1,pid: 0,name: 'body',children: [{id: 2,pid: 1,name: 'title',children: [{id: 3,pid: 1,name: 'div'}]}}]代碼實(shí)現(xiàn):
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=`, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>toTree</title></head><body><script>var source = [{id: 1,pid: 0,name: 'body'}, {id: 2,pid: 1,name: 'title'}, {id: 3,pid: 1,name: 'div'}, {id: 4,pid: 3,name: 'span'}, {id: 5,pid: 3,name: 'icon'}, {id: 6,pid: 4,name: 'subspan'}]function toTree(data) {let result = []if(!Array.isArray(data)) {return result}data.forEach(item => {delete item.children;});let map = {};data.forEach(item => {map[item.id] = item;});data.forEach(item => {let parent = map[item.pid];if(parent) {(parent.children || (parent.children = [])).push(item);} else {result.push(item);}});return val;}console.log(toTree(source))</script></body></html>?
轉(zhuǎn)載于:https://www.cnblogs.com/mengfangui/p/10494601.html
總結(jié)
以上是生活随笔為你收集整理的js 数组 转为树形结构的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 超哥笔记--linux准备知识(1)
- 下一篇: Android jdbc连接mysql报