1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
const listToTree = (array, opt, startPid) => { const obj = { primaryKey: opt.primaryKey || 'key', parentKey: opt.parentKey || 'parentId', titleKey: opt.titleKey || 'title', startPid: opt.startPid || '', currentDept: opt.currentDept || 0, maxDept: opt.maxDept || 100, childKey: opt.childKey || 'children', }; if (startPid) { obj.startPid = startPid; } return toTree(array, obj.startPid, obj.currentDept, obj); };
const toTree = (array, startPid, currentDept, opt) => { if (opt.maxDept < currentDept) { return []; } let child = []; if (array && array.length > 0) { child = array .map((item) => { if (typeof item[opt.parentKey] !== 'undefined' && item[opt.parentKey] === startPid) { const nextChild = toTree(array, item[opt.primaryKey], currentDept + 1, opt); if (nextChild.length > 0) { item['isLeaf'] = false; item[opt.childKey] = nextChild; } else { item['isLeaf'] = true; } item['title'] = item[opt.titleKey]; item['label'] = item[opt.titleKey]; item['key'] = item[opt.primaryKey]; item['value'] = item[opt.primaryKey]; return item; } }) .filter((item) => { return item !== undefined; }); } return child; };
|