다음과 같은 중첩된 개체가 있는 개체 배열이 있습니다.
const arr = [{
id: 0, children: []
}, {
id: 1, children: [{
id: 2, children: []
}, {
id: 3, children: [{
id: 4, children: []
}]
}]
}]; 우리의 임무는 재귀 함수를 작성하는 것입니다. 예를 들어 assignDepth()는 이 배열을 가져와서 각 중첩 객체에 깊이 속성을 할당합니다. id 0을 가진 객체는 깊이 0을 가질 것이고, id 1도 깊이 1을 가질 것이고, id 2와 id 3은 id 1 안에 중첩되기 때문에 그들은 깊이 1을 가질 것이고 id 3 안에 더 중첩되는 id 4는 깊이 2를 가질 것입니다.
따라서 이 함수에 대한 코드를 작성해 보겠습니다. 배열의 끝에 도달할 때까지 하위 개체를 반복적으로 반복하는 간단한 재귀 함수입니다. −
예시
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)); 출력
콘솔의 출력은 -
[
{
"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
}
]