tachybase_todo/packages/plugin-pages/src/utils.ts
chenos dcdb21d398
发布核心框架 (#6)
* api/ui 改名为 server/client

* 微调

* 继续完善 pages

* Fix env file and file mode. (#1)

* Fix: ignore .env file and environment variable names.

* Fix: correct file mode.

* fix: put environment variables together

* fix: separate data and ui resourcer

* feat: collection loader

* feat: redirectTo

* feat: fields & actions & views

* feat: fields & actions

* feat: app & pages & collections...

* feat: collections & pages & permissions...

* Doc: add readme (#2)

* Doc: add README.md.

* Util: add .editorconfig.

* Fix: use glob ignore option instead of additional checking. (#3)

* Fix: typo. (#4)

* feat: permissions

* feat: getCollection & getView actions

* refactor: code cleanup

Co-authored-by: Junyi <mytharcher@users.noreply.github.com>
2020-11-11 15:23:39 +08:00

37 lines
1.3 KiB
TypeScript

export const flatToTree = (flatArray, options) => {
options = {
id: "id",
parentId: "parentId",
children: "children",
...options
};
const dictionary = {}; // a hash table mapping to the specific array objects with their ids as key
const tree = [];
const children = options.children;
flatArray.forEach(node => {
const nodeId = node[options.id];
const nodeParentId = node[options.parentId];
// set up current node data in dictionary
dictionary[nodeId] = {
[children]: [], // init a children property
...node, // add other propertys
...dictionary[nodeId] // children will be replaced if this node already has children property which was set below
};
dictionary[nodeParentId] = dictionary[nodeParentId] || { [children]: [] }; // if it's not exist in dictionary, init an object with children property
dictionary[nodeParentId][children].push(dictionary[nodeId]); // add reference to current node object in parent node object
});
// find root nodes
Object.values(dictionary).forEach(obj => {
if (typeof obj[options.id] === "undefined") {
tree.push(...obj[children]);
}
});
return treeData(tree);
};
function treeData(pages: Array<any>) {
return pages.map(data => {
return {...data, children: data.children && data.children.length ? treeData(data.children) : undefined}
});
}