일단 데이터는 아래와 같이 생김
chains: {
chain1: {
request: {
text: "체인1",
},
children: {
"chain1-1": {
request: {
text: "체인1-1",
},
children: {
"chain1-1-1": {
request: {
text: "체인1-1-1",
},
},
"chain1-1-2": {
request: {
text: "체인1-1-2",
},
},
},
},
"chain1-2": {
request: {
text: "체인1-2",
},
},
},
},
체인2: {
request: {
text: "chain2",
},
children: {
"체인2-1": {
request: {
text: "chain2-1",
},
children: {
"체인2-1-1": {
request: {
text: "chain2-1-1",
},
children: {
"체인2-1-1-1": {
request: {
text: "chain2-1-1-1",
},
children: {
"체인2-1-1-1-1": {
request: {
text: "chain2-1-1-1-1",
},
children: {
"체인2-1-1-1-1-1": {
request: {
text: "chain2-1-1-1-1-1",
},
},
},
},
"체인2-1-1-1-2": {
request: {
text: "chain체인2-1-1-1-2",
},
},
},
},
},
},
"체인2-1-2": {
request: {
text: "chain2-1-2",
},
},
},
},
"체인2-2": {
request: {
text: "chain2-2",
},
},
},
},
}
데이터 안에 데이터 안에 데이터
재귀적 구조?
인터페이스로 정의 하면 아래와 같다
interface InterfaceChain {
[key: string]: {
request: {
text: string;
};
children?: InterfaceChain;
};
}
화면에 이렇게 트리를 그리고 싶음
<div
onClick={() => {
try {
loop(data as InterfaceChain, 0, "loop0,0");
const div = document.getElementById("loop0,0");
div!.id = "";
} catch (error) {}
}}
/>
<div id="loop0,0"></div>
일단 화면
loop 함수에서 트리 그리는 로직을 탈 것이다
체인 데이터들과, 순서, dom element id를 보낸다
const loop = (chain: ChainType, order: number, divId: string) => {
Object.entries(chain).forEach((val, idx) => {
if (val[1]) { // val[0]은 키, val[1]은 value
const div = document.createElement("details"); // 접었다 폈다 하고 싶어서 details/summary 사용
div.className = "mx-3"; // tailwind css
div.id = `loop${order + 1},${idx}`;
const summary = document.createElement("summary");
summary.textContent = val[1].request.text;
summary.className = "m-2";
div.appendChild(summary);
document.getElementById(divId)?.appendChild(div); // 이전에 받아온 dom element 아래에 새로 만든 애 붙임
if (val[1].children) {
if (Object.entries(val[1].children)) { // children이 있으면 재귀함수 실행
loop(val[1].children, order + 1, `loop${order + 1},${idx}`); // 어느 dom 아래에 붙일지, 순서는 몇번째인지 같이 보내줌
}
}
div.id = "";
return;
}
});
};
'Web' 카테고리의 다른 글
[Backend] Express send(), write() 차이 (1) | 2024.01.08 |
---|---|
[Backend] Node.js + Express MVC 기초 세팅 (1) | 2024.01.02 |
[Backend] Django MTV중 TV 해보기 (1) | 2023.10.14 |
[Frontend] axios/fetch headers utf8 한글 오류 (0) | 2023.10.13 |
[Backend] AWS ec2 서버 시간 설정 (0) | 2023.10.12 |