util-helpers
Version:
61 lines (57 loc) • 2.08 kB
JavaScript
;
var tslib = require('tslib');
var ut2 = require('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 (!ut2.isArray(list)) {
return tree;
}
list.forEach(function (item) {
if (ut2.isObject(item)) {
var newItem = nodeAssign === 'spread' ? tslib.__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;
}
module.exports = listToTree;