UNPKG

shu-c-view

Version:

rollup 打包vue组件库框架

86 lines (70 loc) 1.91 kB
import _omit from 'lodash/omit'; /** * @description 将树平铺为数组 * @param { object } tree 数据 * @param { String } children 树形结构关联的属性 */ const getTreeMap = (tree, children = 'children') => { if (!(tree instanceof Array)) return; const treeMap = []; tree.forEach(node => { treeMap.push(...getNodeMap(node, tree, children)); }); return treeMap; }; const getNodeMap = (node, parentNode, children) => { // node.parentNode = JSON.parse(JSON.stringify(parentNode)); const nodeMap = [node]; if (node[children] && node[children].length) { node[children].forEach(item => nodeMap.push(...getNodeMap(item, node, children)) ); } return nodeMap; }; /** * @description 查找节点在树中的路径 * @param {*} tree 树的数据 * @param {*} id 查找的id * @param {*} nodeKey 节点标识符 * @param {*} children 子节点标识 * @returns */ const getNodePath = ({ tree, id, nodeKey = 'id', children = 'children', dataAll = false, needKey }) => { if (!Array.isArray(tree) || tree.length === 0) { return []; } const path = []; const treeFindPath = (childTree, childId, childPath) => { // eslint-disable-next-line no-restricted-syntax for (const item of childTree) { let itemData = null; if (needKey) { itemData = dataAll ? _omit(item, children) : item[needKey]; } else { itemData = dataAll ? _omit(item, children) : item[nodeKey]; } childPath.push(itemData); if (item[nodeKey] === childId) { return childPath; } if (item[children]) { const findChildren = treeFindPath(item[children], childId, childPath); if (findChildren.length) { return findChildren; } } childPath.pop(); } return []; }; return treeFindPath(tree, id, path); }; export { getTreeMap, getNodePath };