# 怎么根据id递归多维数组？

,该数组是一维数组，第一层节点是parent:# 第二层根据第一层id和

5 个回答
``````let arr = [{id:"-1",parent:"#",text:'请选择'},{id:"1",parent:"#",text:'刑事'},{id:"2",parent:"1",text:'安全罪'}];
let arrToTree =(arr, parent='#')=> {
let obj = arr.reduce((acc,cur)=>{
// 根据parent 判断是否相等来归类。true 当前级别
acc[cur.parent == parent].push(cur);
return acc;
},{true:[],false:[]})
// 当前级别
let currentArr = obj[true];
// 其他级别
let otherArr = obj[false];
return currentArr.map(item=>{
// 递归得到子级
let children = arrToTree(otherArr, item.id);
return {...item, children};
})
}
arrToTree(arr, '#');
``````

``````var arr = [
{ id: '-1', parent: '#', text: '1' },
{ id: '1', parent: '#', text: '2' },
{ id: '2', parent: '4', text: '3' },
{ id: '3', parent: '2', text: '4' },
{ id: '4', parent: '6', text: '5' }
];
console.log(sum(0, arr));

function sum(index,data) {
if(!data[index+1]) return 'no';
if(data[index].id == data[index+1].parent) return data[index+1];
return sum(index+1,data);
}``````
``````function toTree(data) {
const res = [];
const map = {};
data.forEach((item) => {
map[item.id] = item
})
data.forEach((item) => {
let parentItem = map[item.parent];
if(parentItem) {
(parentItem.children || (parentItem.children = [])).push(item)
} else {
res.push(item)
}
})
return res
}``````

var a:any = [{ id: 1, name: 3, pid: -1, children: [] }];
const map = new Map();

// 将所有的记录以下方便取
for (const t of a) {
map.set(t.id, t);
t.children = [];
}

// 遍历添加子元素
for (const t of a) {
if (t.pid !== -1) {

``````const e = map.get(t.pid);
e.children.push(e);``````

}
}

console.log(map);

// 从map里面去除pid为

``````var a = [
{ id: "-1", parent: "#", text: "1" },
{ id: "1", parent: "#", text: "2" },
{ id: "2", parent: "4", text: "3" },
{ id: "3", parent: "2", text: "4" },
{ id: "4", parent: "6", text: "5" },
];
const map = new Map();

// 将所有的记录以下方便取
for (const t of a) {
map.set(t.id, t);
t.children = [];
}
map.forEach((t) => {
if (t.parent !== "#") {
const parent = map.get(t.parent);
if (parent) {
parent.children.push(t);
}
}
});
const result = [];
map.forEach((e) => {
result.push(e);
});

console.log(result);

// 从map里面去除pid为
``````
``````function list2tree(list) {
var ret, cache = {};
for (var i = 0; i < list.length; ++i) {
var item = list[i];
var obj = cache[item.id] = { children: [] };
for (var key in item) obj[key] = item[key];
}
for (var key in cache) {
var obj = cache[key];
var id = obj.parent;
if (cache[id]) cache[id].children.push(obj);
else cache[id] = ret = { id: id, children: [obj] };
}
return ret;
}
console.log(list2tree([{
"id": "-1",
"parent": "#",
"text": "请选择"
},
{
"id": "1",
"parent": "#",
"text": "刑事案由"
},
{
"id": "2",
"parent": "1",
"text": "危害国家安全罪"
},
{
"id": "3",
"parent": "2",
"text": "背叛国家罪"
},
{
"id": "4",
"parent": "2",
"text": "分裂国家罪"
},
{
"id": "5",
"parent": "2",
"text": "煽动国家罪"
}
]));``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进