[js] Convert the data returned by the background into a tree structure through parentId and id

/**
 * 将后台数据转换为树形结构
 * @param pid   是你拿到的数据中的parentId
 * @param arr 	你拿的数据
 * @returns 
 */
 export const getTrees = (pid: string | number, arr: any) => {
    
    
  return arr.filter((item: any) => item.parentId === pid).map((item: any) => {
    
    
    item.children = getTrees(item.id, arr)
    return item
  })
}

Like the cascader component of elementplus, the cascader component of vant, etc., they all have the data format they require, so after converting the data structure with the above method, you need to manipulate the attribute value again

/**
 * 将树形结构数据转换为级联要求的字段
 * @param tree 
 * @param map 
 * @returns 
 */
export const converTree = (tree: any, map: any = {
    
    
    label: 'name',
    value: 'id',
    children: 'children'
}) => {
    
    
	const result: any = [];
	tree.forEach((item: any) => {
    
    
		let value = item[ map.value ];
		let label = item[ map.label ];
		let children = item[ map.children ];
		if (children) {
    
    
		  children = converTree(children, map);
		}
		result.push({
    
     value, label, children });
	})
	return result
}

use:

//  这个0是拿到的数据里面最顶级的parentId的值,list就是拿到的数据
cascaderOptions.value = converTree(getTrees(0, list))

Guess you like

Origin blog.csdn.net/bbt953/article/details/130388127