js递归树形结构
下面是代码。
// An highlighted block
function filterArray(data, parent) {
let tree = [];
let temp;
for (let i = 0; i < data.length; i = i + 1) {
if (data[i].pid == parent) {
var obj = data[i];
temp = filterArray(data, obj.id);
if (temp.length > 0) {
obj.children = temp;
}
tree.push(obj);
}
}
console.log(tree)
return tree;
}
下面是平行结构数据
// An highlighted block
[
{
children: [],
createTime: 2022-04-03T17:05:46.422Z,
updateTime: 2022-04-03T17:05:46.422Z,
_id: 6249b25c74053a88c752fa7d,
xid: 'root',
articleName: '测试一级2',
articleType: 1,
pid: null
},
{
children: [],
createTime: 2022-04-03T17:05:46.422Z,
updateTime: 2022-04-03T17:05:46.422Z,
_id: 6249b26f74053a88c752fa7e,
xid: 'people',
articleName: '测试二级1',
articleType: 1,
pid: 6249b24d74053a88c752fa7c
},
{
children: [],
createTime: 2022-04-03T17:05:46.422Z,
updateTime: 2022-04-03T17:05:46.422Z,
_id: 6249b44e74053a88c752fa7f,
{
children: [],
createTime: 2022-04-03T17:05:46.422Z,
updateTime: 2022-04-03T17:05:46.422Z,
_id: 6249b25c74053a88c752fa7d,
xid: 'root',
articleName: '测试一级2',
articleType: 1,
pid: null
}
]
结果
// An highlighted block
{
"data": [
{
"children": [
{
"children": [
{
"children": [],
"createTime": "2022-04-03T17:08:35.014Z",
"updateTime": "2022-04-03T17:08:35.014Z",
"_id": "6249b44e74053a88c752fa7f",
"xid": "article",
"articleName": "文章1",
"articleType": 0,
"pid": "6249b26f74053a88c752fa7e"
}
],
"createTime": "2022-04-03T17:08:35.014Z",
"updateTime": "2022-04-03T17:08:35.014Z",
"_id": "6249b26f74053a88c752fa7e",
"xid": "12312",
"articleName": "测试二级1",
"articleType": 1,
"pid": "6249b25c74053a88c752fa7d"
}
],
"createTime": "2022-04-03T17:08:35.014Z",
"updateTime": "2022-04-03T17:08:35.014Z",
"_id": "6249b25c74053a88c752fa7d",
"xid": "12312",
"articleName": "测试一级2",
"articleType": 1,
"pid": null
}
]
}