扁平数组转换成tree结构

扁平数组转换成tree结构【直接上图】

    


 

来源: StackOverflow的印度老哥写的

复制代码
 1 // Data Set
 2 // One top level comment 
 3 var comments = [{
 4     id: 1,
 5     parent_id: null
 6 }, {
 7     id: 2,
 8     parent_id: 1
 9 }, {
10     id: 3,
11     parent_id: 1
12 }, {
13     id: 4,
14     parent_id: 2
15 }, {
16     id: 5,
17     parent_id: 4
18 }];
19 
20 const nest = (items, id = null, link = 'parent_id') =>
21   items
22     .filter(item => item[link] === id)
23     .map(item => ({ ...item, children: nest(items, item.id) }));
24 
25 nest(comments);
复制代码
posted @ 2020-08-20 10:44  初夏の雨  阅读(231)  评论(0)    收藏  举报