Cho mảng object có children lồng nhau. Viết hàm đệ quy assignDepth() gán property depth cho mỗi object: gốc depth 0, con depth 1, cháu depth 2...
Dữ liệu:
const arr = [
{ id: 0, children: [] },
{ id: 1, children: [
{ id: 2, children: [] },
{ id: 3, children: [
{ id: 4, children: [] }
]}
]}
];Ví dụ
const arr = [
{ id: 0, children: [] },
{ id: 1, children: [
{ id: 2, children: [] },
{ id: 3, children: [
{ id: 4, children: [] }
]}
]}
];
const assignDepth = (arr, depth = 0, index = 0) => {
if (index < arr.length) {
arr[index].depth = depth;
if (arr[index].children.length) {
return assignDepth(arr[index].children, depth + 1, 0);
}
return assignDepth(arr, depth, index + 1);
}
return;
};
assignDepth(arr);
console.log(JSON.stringify(arr, undefined, 4));Kết quả
Đầu ra trong console sẽ là:
[
{
"id": 0,
"children": [],
"depth": 0
},
{
"id": 1,
"children": [
{
"id": 2,
"children": [],
"depth": 1
},
{
"id": 3,
"children": [
{
"id": 4,
"children": [],
"depth": 2
}
],
"depth": 1
}
],
"depth": 0
}
]