util-helpers
Version:
59 lines (56 loc) • 2.08 kB
JavaScript
import { __assign } from 'tslib';
import { isArray, isObject } from 'ut2';
function processEmptyChildren(arr, options) {
var _a = options.childrenField, childrenField = _a === void 0 ? 'children' : _a, _b = options.emptyChildrenValue, emptyChildrenValue = _b === void 0 ? 'none' : _b;
arr.forEach(function (item) {
if (item[childrenField].length <= 0) {
if (emptyChildrenValue === 'null') {
item[childrenField] = null;
}
else {
delete item[childrenField];
}
}
else {
processEmptyChildren(item[childrenField], options);
}
});
}
function listToTree(list, options) {
if (options === void 0) { options = {}; }
var _a = options.keyField, keyField = _a === void 0 ? 'id' : _a, _b = options.parentField, parentField = _b === void 0 ? 'pid' : _b, _c = options.childrenField, childrenField = _c === void 0 ? 'children' : _c, _d = options.emptyChildrenValue, emptyChildrenValue = _d === void 0 ? 'none' : _d, _e = options.nodeAssign, nodeAssign = _e === void 0 ? 'spread' : _e;
var tree = [];
var record = {};
if (!isArray(list)) {
return tree;
}
list.forEach(function (item) {
if (isObject(item)) {
var newItem = nodeAssign === 'spread' ? __assign({}, item) : item;
var id = newItem[keyField];
var pid = newItem[parentField];
if (record[id]) {
newItem[childrenField] = record[id];
}
else {
newItem[childrenField] = record[id] = [];
}
if (pid) {
if (!record[pid]) {
record[pid] = [newItem];
}
else {
record[pid].push(newItem);
}
}
else {
tree.push(newItem);
}
}
});
if (emptyChildrenValue !== 'array') {
processEmptyChildren(tree, options);
}
return tree;
}
export { listToTree as default };