1.1.1 • Published 6 years ago
to-json-tree v1.1.1
to-json-tree
Convert JSON to JSON tree (将具有层级关系的扁平结构JSON数据转换为JSON树)
Installing
Using npm:
$ npm install to-json-tree
Import
Using import:
import toJsonTree from 'to-json-tree'
Using require:
const toJsonTree = require('to-json-tree')
Example
/*
toJsonTree用于将具有层级关系的扁平结构数据转换成json树
1.调用方法:toJsonTree(oData,param);
2.关于oData和params;
1)oData即带有层级关系的原数据,它是一个数组,为必传参数
2)params为非必传参数,它的默认值为{ rootKey: 'id', rootVal: 0, selfKey: 'id', parentKey: 'parentId' }
其中rootKey和rootVal分别表示能确定某元素为树的根元素的key值和value值,selfKey和parentKey分别表示某元素能定
位自身和父元素的key值;当你的数据与与默认参数不一致时,你可以参考参考示例2进行配置
3.方法返回值中banch代表json树中往上生长的树枝
*/
// 示例1(原数据参数与默认参数一致)
var oData1 = [
{ id: 0, parentId: 0, text: '000' },
{ id: 1, parentId: 0, text: '111' },
{ id: 2, parentId: 1, text: '222' },
{ id: 3, parentId: 1, text: '333' },
{ id: 4, parentId: 2, text: '444' }
];
var res1 = toJsonTree(oData1);
console.log('res1', res1);
// 示例2(原数据参数与默认参数不一致)
var oData2 = [
{ id: 6, iType: 'root', pId: 6, text: '666' },
{ id: 1, iType: 'not_root', pId: 6, text: '111' },
{ id: 2, iType: 'not_root', pId: 1, text: '222' },
{ id: 3, iType: 'not_root', pId: 1, text: '333' },
{ id: 4, iType: 'not_root', pId: 2, text: '444' }
];
var param = { rootKey:'iType', rootVal:'root', parentKey:'pId' };//哪个不匹配就配置哪个
var res2 = toJsonTree(oData2,param);
console.log('res2', res2);