js(typescript) 子孫の要素を再帰処理で取得する
やりたいこと
[{id:"XXX", parentsId:"", contents: ...},{id:"yyy", parentsId:"XXX", contents: ...}]
こんな感じのデータ構造のコンテンツを、
{id:"XXX", parentId:"",contents:..., descendants:[{id:"yyy", parentsId:"XXX", contents: ...,descendants:[]}]}
という形で階層化したい。
書いた
Typescriptで書いてます。
type originalInfo = { id:string, parentsId:string, contents:any, }; type NodeInfo = { data: originalInfo; descendants: NodeInfo[]; }; // Idの子要素を探して返却する処理 function findDescendants(Id: string, nodelist: NodeInfo[]): NodeInfo[] { let target = []; let other = []; for (let n of nodelist) { if (n.parentId === Id) { target.push(n); } else { other.push(n); } } for (let t of target) { const d = findDescendants(t.Id, other); t.descendants = d; } return target; } // 階層化処理 function createNodeList(originalData: originalInfo[]): NodeInfo[] { let preNodeList: NodeInfo[] = []; originalData.forEach((c: originalInfo, index) => { preNodeList.push({ id c.id, parentId: c.parentId, descendants: [], }); }); let parentList: NodeInfo[] = []; let childList: NodeInfo[] = []; // 親要素と子要素とで分割 for (let node of preNodeList) { if (node.parentId) { childList.push(node); } else { parentList.push(node); } } for (let p of parentList) { const descendants = findDescendants(p.id,childList); p.descendants = descendants; } return parentList; } function mainFunction(originalData:originalInfo[]) { const nodeList = createNodeList(originalData) }