Data to be transformed:
var arr = [
{
id: 1, name: '小组1', pid: 0},
{
id: 2, name: '小组2', pid: 1},
{
id: 3, name: '小组3', pid: 1},
{
id: 4, name: '小组4', pid: 3},
{
id: 5, name: '小组5', pid: 4}
]
solution:
1. Recursion
The main idea is to provide a recursive getChildren method, which recursively finds subsets.
/**
* 递归查找,获取children
*/
const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = {
...item, children: []};
result.push(newItem);
getChildren(data, newItem.children, item.id);
}
}
}
/**
* 转换方法
*/
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid)
return result;
}
2. Without recursion,
the main idea of traversing twice is to first convert the data Map
to storage, and then use it while traversing 对象的引用
to directly Map
find the corresponding data for storage
function arrayToTree(items) {
const result = []; // 存放结果集
const itemMap = {
}; //
// 先转成map存储
for (const item of items) {
itemMap[item.id] = {
...item, children: []}
}
for (const item of items) {
const id = item.id;
const pid = item.pid;
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}
3. Without recursion, the
main idea of a traversal (best performance and shortest time-consuming) is to first convert the data Map
to storage, and then use it while traversing 对象的引用
to directly Map
find the corresponding data for storage. The difference is stored when traversing Map
, and there is a corresponding relationship to be found. Performance will be better.
function arrayToTree(items) {
const result = []; // 存放结果集
const itemMap = {
}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}