import cloneDeep from 'lodash/cloneDeep';
// 树的解析默认配置
const configDefault = {
'key': 'id',
'parentKey': 'parentId',
'text': 'name',
'childKey': 'children',
};
const treeFormat = (data, config) => {
const copyData = cloneDeep(data);
const { parentKey, text, key, childKey } = { ...configDefault, ...config };
let i;
let l;
if (copyData.constructor.name === 'Array') {
// 根目录
const root = [];
const tmpMap = [];// 缓存数组
// 初始化数据
for (i = 0, l = copyData.length; i < l; i += 1) {
copyData[i].title = copyData[i][text];
tmpMap[copyData[i][key]] = copyData[i];
}
for (i = 0, l = copyData.length; i < l; i += 1) {
if (tmpMap[copyData[i][parentKey]] && copyData[i][key] !== copyData[i][parentKey]) {
if (!tmpMap[copyData[i][parentKey]][childKey]) {
tmpMap[copyData[i][parentKey]][childKey] = [];
}
copyData[i].parentName = tmpMap[copyData[i][parentKey]][text];
tmpMap[copyData[i][parentKey]][childKey].push(copyData[i]);
} else {
root.push(copyData[i]);
}
}
return root;
}
return copyData;
};
export default treeFormat;
import cloneDeep from 'lodash/cloneDeep';
// 树的解析默认配置
const configDefault = {
'key': 'id',
'parentKey': 'parentId',
'text': 'name',
'childKey': 'children',
};
const treeFormat = (data, config) => {
const copyData = cloneDeep(data);
const { parentKey, text, key, childKey } = { ...configDefault, ...config };
if (copyData.constructor.name === 'Array') {
// 根目录
const root = [];
const tmpMap = {};// 缓存数组
// 初始化数据
copyData.map(item => {
item.title = item[text];
tmpMap[item[key]] = item;
return item;
});
copyData.map(item => {
if (tmpMap[item[parentKey]] && item[key] !== item[parentKey]) {
if (!tmpMap[item[parentKey]][childKey]) {
tmpMap[item[parentKey]][childKey] = [];
}
item.parentName = tmpMap[item[parentKey]][text];
tmpMap[item[parentKey]][childKey].push(item);
} else {
root.push(item);
}
return item;
});
return root;
}
return copyData;
};
export default treeFormat;
//渲染数据
function mapCate1ToOptions(categorys) {
return categorys && categorys.map((category) => {
return Object.assign({}, {
title: category.codeName,
value: category.code,
key:category.code,
isLeaf: false,
children: getChildCategorys(category)
});
}
)
}
function getChildCategorys(categoryCur) {
return categoryCur.children && categoryCur.children.map((category) => {
return Object.assign({}, {
title: category.codeName,
value: category.code,
key: category.code,
isLeaf: category.children ? false : true,
children: category.children ? getChildCategorys(category) : null
});
});
}