JS 三元组转树形结构
/** * 三元组转换成树形结构 * @param nodes 节点数组 * @param relations 关系数据 * @param idName 节点ID属性名称 * @param sourceName 关系起始节点ID属性名称 * @param targetName 关系终止节点ID属性名称 * @returns {[]} */ const tripletToTree = function ({nodes, relations, idName, sourceName, targetName}) { idName = idName ? idName : 'id'; sourceName = sourceName ? sourceName : 'sourceId'; targetName = targetName ? targetName : 'targetId'; console.log(nodes); // * 先生成parent建立父子关系 const nodeObj = {}; nodes.forEach((item) => { console.log(item[idName]); nodeObj[item[idName]] = item; }); const parentList = []; relations.forEach((item) => { // item.hasChildren = false; const parent = nodeObj[item[sourceName]]; const child = nodeObj[item[targetName]]; if (parent && child) { child.isChild = true; parent.children = parent.children || []; parent.children.push(nodeObj[item[targetName]]); } // parent.hasChildren = true; }); console.log(nodeObj); Reflect.ownKeys(nodeObj).forEach(key => { if (!nodeObj[key].isChild) { parentList.push(nodeObj[key]); } }); return parentList; }
大概写了一下,可能会有些许不足或bug,可在评论区留言供我改进,万分感谢!