码迷,mamicode.com
首页 > 编程语言 > 详细

数组转为树形结构以及树形结构平铺成数组

时间:2020-06-15 09:33:39      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:color   title   log   col   length   nod   new   console   结构   

 1 var source = [
 2         {
 3           id: 1,
 4           pid: 0,
 5           name: ‘body‘,
 6         },
 7         {
 8           id: 5555,
 9           pid: 0,
10           name: ‘script‘,
11         },
12         {
13           id: 55551,
14           pid: 5555,
15           name: ‘js‘,
16         },
17         {
18           id: 2,
19           pid: 1,
20           name: ‘title‘,
21         },
22         {
23           id: 3,
24           pid: 1,
25           name: ‘div‘,
26         },
27         {
28           id: 4,
29           pid: 3,
30           name: ‘span‘,
31         },
32         {
33           id: 5,
34           pid: 3,
35           name: ‘icon‘,
36         },
37         {
38           id: 6,
39           pid: 4,
40           name: ‘subspan‘,
41         },
42       ];
43 
44       function toTree(data) {
45         let result = [];
46         if (!Array.isArray(data)) {
47           return result;
48         }
49         data.forEach((item) => {
50           delete item.children;
51         });
52         let map = {};
53         data.forEach((item) => {
54           map[item.id] = item;
55         });
56         data.forEach((item) => {
57           let parent = map[item.pid];
58           if (parent) {
59             (parent.children || (parent.children = [])).push(item);
60           } else {
61             result.push(item);
62           }
63         });
64         return result;
65       }
66       console.log("树结构===", toTree(source));
67 
68 
69       let newTree = toTree(source);
70       var resultArr = [];
71       function flat(nodes, parentId) {
72         if (!nodes || nodes.length === 0) return [];
73         nodes.forEach((node) => {
74             resultArr.push({ ...node });
75           return flat(node.children, node.id);
76         });
77       }
78 
79       flat(newTree, 0);
80       console.log("铺平===", resultArr)

 

数组转为树形结构以及树形结构平铺成数组

标签:color   title   log   col   length   nod   new   console   结构   

原文地址:https://www.cnblogs.com/yuhanao/p/13128998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!