12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- /**
- * 数组 转 Tree
- * @param {*} arr
- * @param {*} parent
- * @param {*} key
- * @returns
- */
- export function arr2Tree(arr = [], parent = "parentId", key = "key") {
- // 转换为字典
- const dict = arr.reduce((acc, item) => {
- return {
- ...acc,
- [item[key]]: {
- ...item,
- children: [],
- },
- };
- }, {});
-
- // // 查找顶级结点
- // const getRootNode = (node) => {
- // const found = arr.filter((x) => node[parentId] === x[key])[0];
-
- // return !found ? dict[node[key]] : getRootNode(found);
- // };
-
- // 挂载父子节点
- const tree = [];
- for (let item of arr) {
- const it = dict[item[key]];
- const parentNodeId = it[parent];
- const parentNode = dict[parentNodeId];
-
- if (!parentNode) {
- tree.push(it);
- } else {
- dict[parentNodeId].children.push(it);
- }
- }
- return [tree, dict];
- }
-
- /**
- * 深度展平数组
- * @param {*} arr
- * @returns
- */
- export function flatten(arr = []) {
- return arr.reduce((acc, it) => {
- const list = Array.isArray(it) ? flatten(it) : it;
- return acc.concat(list);
- }, []);
- }
-
- /**
- * 深度数组去重
- * @param {*} arr
- */
- export function uniq(arr = []) {
- const list = flatten(arr);
- return list.reduce((acc, it) => {
- return acc.indexOf(it) > -1 ? acc : acc.concat(it);
- }, []);
- }
|