# Tree管理 **Repository Path**: Luomenghao/tree-manage ## Basic Information - **Project Name**: Tree管理 - **Description**: tree日常方法封装 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-01-14 - **Last Updated**: 2022-01-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Tree 数据日常操作 ## 方法说明 |方法名| 说明 | 参数 | 返回值|备注 |--|--|--|--|--| | getChildrenById(key) | 获取孩子 | 父亲ID | Array | getParentsById(key1, key2) | 获取父亲 | key1: 查找的id, key2: 回调函数 | Array | getNameById(key) | 获取名称 | key: id | String | getNameByIdList(key1, key2, ...keyn) | 获取名称(多个) | key:id | Object
{list: [], map: {}} | hasChild(key) | 是否存在子集 | key:id | Boolean | getChildSize(key) | 孩子个数 | key:id | Number ## 初始化 ```javascript const treeObj = new Tree([{ id: '1', parentId: 0, name: '四川省', children: [ { id: '1-1', parentId: '1', name: '成都市', children: [ { id: '1-1-1', parentId: '1-1', name: '武侯区' }, { id: '1-1-2', parentId: '1-1', name: '金牛区' }, ] }, { id: '1-2', parentId: '1', name: '绵阳市' }, { id: '1-3', parentId: '1', name: '德阳市' } ] }]) ``` ## 1.通过 id 获取儿子 ```javascript const parentId = '1-1' // 父ID const chidlren = treeObj.getChildrenById(parentId) console.log(parentId) ``` ## 2.通过 id 获取父亲(根) ```javascript /** * id {String|Number}查找的id * format {Function} 格式化函数,不传递则返回默认 item */ const parents = treeObj.getParentsById(id, function format(item){ return item.name }) console.log(parents) // array [rootName, ..., parentName, name] ``` ## 3.通过 id 获取名称 ```javascript /** * id {String|Number}查找的id */ const name = treeObj.getNameById(id) console.log(name) // string ``` ## 3.通过 id 获取名称(多个) ```javascript /** * id {String|Number}查找的id */ const names = treeObj.treeObj.getNameByIdList(id1, id2, id3) console.log(names) // Object {list: [name1, name2, name3], map: {id1: name1, id2: name2, id3: name3}} ``` ## 4.是否存在孩子 ```javascript /** * id {String|Number}查找的id */ const hasChild = treeObj.hasChild(id) // 传入多个id console.log(hasChild) // true || false ``` ## 5.获取孩子数量 ```javascript /** * id {String|Number}查找的id */ const childCount = treeObj.getChildSize(id) // 传入多个id console.log(childCount) // 0 || 其他 ```