shu-c-view
Version:
rollup 打包vue@2.7组件库框架
86 lines (71 loc) • 1.9 kB
JavaScript
import _omit from 'lodash/omit';
/**
* @description 将树平铺为数组
* @param { object } tree 数据
* @param { String } children 树形结构关联的属性
*/
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;
};
export const getTreeMap = (tree, children = 'children') => {
if (!(tree instanceof Array)) {
return;
}
const treeMap = [];
tree.forEach(node => {
treeMap.push(...getNodeMap(node, tree, children));
});
return treeMap;
};
/**
* @description 查找节点在树中的路径
* @param {*} tree 树的数据
* @param {*} id 查找的id
* @param {*} nodeKey 节点标识符
* @param {*} children 子节点标识
* @returns
*/
export 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);
};