|
| 1 | +# smart-array-to-tree |
| 2 | +[](https://travis-ci.org/internet5/smart-array-to-tree)<br /> |
| 3 | +快速地转换数据量比较大的数组为树结构,转换数组长度为46086的组数时,只花了大约0.1秒的时间,而其他转换工具对于这个数据量要么就是转换不正确,要么就是直接挂掉 |
| 4 | +# 安装 && 用法 |
| 5 | + |
| 6 | +在node中: |
| 7 | +```shell |
| 8 | +$ npm i smart-arraytotree --save |
| 9 | +``` |
| 10 | +```javascript |
| 11 | +var smartArrayToTree = require('../index.js'); |
| 12 | +var fetch = require('node-fetch'); |
| 13 | +//get test data length 46086 |
| 14 | +fetch('https://raw.githubusercontent.com/internet5/smart-array-to-tree/master/example/data.json').then(function(response) { |
| 15 | + return response.json(); |
| 16 | +}).then(function(data) { |
| 17 | + //start time |
| 18 | + console.log(new Date()); |
| 19 | + //transform |
| 20 | + let tree = smartArrayToTree(data, { id:'regionId', pid:'parentId', firstPid:null }); |
| 21 | + //end time |
| 22 | + console.log(new Date()); |
| 23 | +}).catch(function(e) { |
| 24 | + console.log(e); |
| 25 | +}); |
| 26 | +/*console*/ |
| 27 | +//2017-11-21T09:51:37.930Z |
| 28 | +//2017-11-21T09:51:37.979Z |
| 29 | + ``` |
| 30 | + |
| 31 | +在浏览器中: |
| 32 | +```html |
| 33 | +<script src="smartArrayToTree.js"></script> |
| 34 | +``` |
| 35 | +```html |
| 36 | +<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" |
| 37 | + crossorigin="anonymous"></script> |
| 38 | + <script src="smartArrayToTree.js"></script> |
| 39 | + <script> |
| 40 | + window.onload = function () { |
| 41 | + $.getJSON("https://raw.githubusercontent.com/internet5/smart-array-to-tree/master/example/data.json", function (data) { |
| 42 | + console.log(new Date()); |
| 43 | + var tree = smartArrayToTree(data, { id: 'regionId', pid: 'parentId', firstPid: null }); |
| 44 | + console.log(new Date()); |
| 45 | + console.log(tree) |
| 46 | + }); |
| 47 | + } |
| 48 | + </script> |
| 49 | +``` |
| 50 | +## API |
| 51 | +### `smartArrayToTree(data, [options])` |
| 52 | + |
| 53 | +#### 参数 |
| 54 | +- **Array** `data`: 数组数据 |
| 55 | +- **Object** `options`: 包含下列属性的配置对象: |
| 56 | + - `id` (String): 数据的ID属性名称. 默认值: 'id' |
| 57 | + - `pid` (String): 数据的父ID属性名称. 默认值: 'pid' |
| 58 | + - `children` (String): 返回树结构对象中子节点属性名称. 默认值: 'children' |
| 59 | + - `firstPid` (String): 将作为树结构顶层节点的父节点值 . 默认值: null |
| 60 | + |
| 61 | +#### 返回 |
| 62 | +- **Array**: 返回转换后的树结构数据 |
0 commit comments