2017-09-28 4 views
0

여기서 I는 루프를 통해 원하는 JSON 개체이다동적 객체 중첩 루프 JS

{ 
    node: 'tree', 
text: 'Main Node', 
    childs:[ 
     { 
     node: 'tree', 
     text: 'First Child', 
     childs:[{ 
       node: 'tree', 
       text: 'first child child' 
       }....] 
     },{ 
     node: 'tree', 
     text: '2nd Child', 
     childs:[{ 
       node: 'tree', 
       text: '2nd child child' 
       }...] 
     }...] 
} 

여기 JSON 제 1 타입이다. 문제는 json이 동적이며 자식 요소가 다른 조건에 따라 달라진다는 것입니다. 그래서 json을 통해 반복하고 리프를 추가하고 싶습니다. 마지막 중첩 된 요소의 끝까지 true. 여기에 무엇을 원하는입니다 :

당신은 재귀 함수와 함께 할 수
{ 
     node: 'tree', 
    text: 'Main Node', 
     childs:[ 
      { 
      node: 'tree', 
      text: 'First Child', 
      childs:[{ 
        node: 'tree', 
        text: 'first child child', 
        leaf: true // i want to add this node to every last one 
        }] 
      },{ 
      node: 'tree', 
      text: '2nd Child', 
      childs:[{ 
        node: 'tree', 
        text: '2nd child child', 
        leaf: true 
        }] 
      }] 
    } 
+0

합니까 [이 답변] (https://stackoverflow.com/a/15268692/6836963)에서 또 다른 질문은 도움이됩니까? –

+0

아니요, 내 json 객체 중첩 요소를 알 수 없기 때문입니다. 그것은 10 단계까지 중첩 될 수 있습니다. 그리고 전 단계를 미리 알지 못합니다. –

+0

개체 키가 있는지 확인할 수 없습니까? 'hasOwnProperty'처럼? –

답변

0

:

let objt = { 
    node: 'tree', 
    text: 'Main Node', 
    childs: [ 
     { 
      node: 'tree', 
      text: 'First Child', 
      childs: [{ 
       node: 'tree', 
       text: 'Main Node' 
      }] 
     }, { 
      node: 'tree', 
      text: '2nd Child', 
      childs: [{ 
       node: 'tree', 
       text: '2nd child child' 
      }] 
     }] 
}; 


function setLeaf(objt) { 
    if (!objt.childs) { 
     objt.leaf = true; 
    } else { 
     objt.childs.forEach(child => setLeaf(child)) 
    } 
} 

setLeaf(objt);