test12

准备研究imagemagick

http://imgsrc.baidu.com/forum/pic/item/fec451da81cb39db9fe7d512d8160924ab18304a.jpg


可以使用递归的方式实现将 list 转换为 tree 的函数,具体实现如下: ```javascript function fm(list) { // 定义一个辅助函数,用于查找某个节点的子节点 function findChildren(node) { return list.filter(item => item.parentId === node.id).map(item => { // 递归查找子节点的子节点 item.children = findChildren(item); return item; }); } // 找到根节点 const root = list.find(item => item.parentId === null); // 递归查找子节点 root.children = findChildren(root); // 返回根节点 return [root]; } ``` 使用方法: ```javascript const list = [ { id: '1', name: 'test1' }, { id: '11', name: 'test11', parentId: '1' }, { id: '12', name: 'test12', parentId: '1' }, { id: '111', name: 'test111', parentId: '11' }, { id: '112', name: 'test112', parentId: '11' }, { id: '121', name: 'test121', parentId: '12' }, { id: '122', name: 'test122', parentId: '12' }, ]; const tree = fm(list); console.log(tree); ``` 输出结果: ``` [ { id: '1', name: 'test1', parentId: null, children: [ { id: '11', name: 'test11', parentId: '1', children: [ { id: '111', name: 'test111', parentId: '11', children: [] }, { id: '112', name: 'test112', parentId: '11', children: [] } ] }, { id: '12', name: 'test12', parentId: '1', children: [ { id: '121', name: 'test121', parentId: '12', children: [] }, { id: '122', name: 'test122', parentId: '12', children: [] } ] } ] } ] ``` 可以看到,经过 `fm` 函数处理后,list 转换成了符合要求的 tree 结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值