array2tree
v1.1.3
Published
array to tree,depend on id and pid ## 一维数组转换为树型结构
Downloads
12
Readme
array2tree
中文.md https://github.com/lihang90/array2tree
Convert array to tree, array item id is related pid default. Defined yourself related params in parameter you can.
Just like
[
{
id: 1,
pid: 0,
name: 'level 1'
},
{
id: 2,
pid: 1,
name: 'level 2'
}
...
]
convert to
[{
id: 1,
pid: 0,
name: 'level 1',
children: [
{
id: 2,
pid: 1,
name: 'level 2',
children: [...]
}
]
},...]
How to use
- npm install
$ npm install array2tree --save
- use
const array2tree = require('array2tree');
const testArr = [
{
id: 1,
pid: 0,
name: 'level 1'
},
{
id: 2,
pid: 1,
name: 'level 2'
},
{
id: 3,
pid: 2,
name: 'level 3'
}
];
const tree = array2tree(testArr);
console.log(tree);
/*
[{
id: 1,
pid: 0,
name: 'level 1',
children: [
{
id: 2,
pid: 1,
name: 'level 2',
children: [
{
id: 3,
pid: 2,
name: 'level 3',
children: []
}
]
}
]
}]
*/
- use parameter by yourself
const array2tree = require('array2tree');
const testArr = [
{
myId: 1,
parentId: 0,
name: 'level 1'
},
{
myId: 2,
parentId: 1,
name: 'level 2'
},
{
myId: 3,
parentId: 2,
name: 'level 3'
}
];
const tree = array2tree(testArr, 'myId', 'parentId');
console.log(tree);
/*
[{
myId: 1,
parentId: 0,
name: 'level 1',
children: [
{
myId: 2,
parentId: 1,
name: 'level 2',
children: [
{
myId: 3,
parentId: 2,
name: 'level 3',
children: []
}
]
}
]
}]
*/
How to test
$ npm install && npm test