扁平结构 转为 树形/森林结构

扁平结构=>树形/森林结构

  1. 转数形(学习大佬的)
    输入类型:扁平数组,返回类型:树形数组
convert2: function (arr) {
	let result = [];
	let parentNode = arr.find( value => value._parentId == 0 );
	let children = arr.filter( value => value._parentId !=0 );
	let mounter = ( parentNode, children ) => {
		children.forEach(( child, index ) => {
				if(child._parentId == parentNode.Id){
					let remainChildren = JSON.parse(JSON.stringify(children));
					remainChildren.splice(index, 1);
					parentNode.children = parentNode.children || [];
					parentNode.children.push( child );
					mounter( child, remainChildren );
				}
			});
	};
	mounter(parentNode, children);
	result.push(parentNode);
	return result;
}
  1. 转树形/森林形(学习大佬的)

你可能感兴趣的:(算法)