在 JavaScript/TypeScript 中表示同一类型对象的未知深度树的最佳方法?
Best way to represent a tree of unknown depth of the same type of object in JavaScript/TypeScript?
这里显而易见的答案是用一个 class 表示对象,然后是对父对象的引用(如果有的话)。跨树的查询将从树的给定节点和 return 该节点的所有父对象开始。每个节点将只有一个直接父节点。
有没有更好的方法从计算上或从软件设计的角度来做到这一点?
编辑:寻找计算复杂性改进建议或可维护性建议。内存在这里不是一个大问题。
@Thomas a relational one. Not sure what our team's opinion is on stored procs but if there is compelling enough reason to use them I'm sure I can make the case.
在关系数据库中,我会使用 common-table-expression
WITH foo AS
(
-- your start node
SELECT *
FROM MyData AS d
WHERE d.id = 123
UNION ALL
-- traversing up
SELECT parent.*
FROM MyData AS parent
JOIN foo AS child
ON parent.id = child.parentId
)
-- selecting the data you want to return from the CTE
SELECT * FROM foo;
在 JS 术语中,这里描述上述查询的作用:
// initial SELECT
var foo = myData.filter(item => item.id === 123);
// UNION ALL + SELECT with JOIN onto `foo`
for (let i = 0; i < foo.length; ++i) {
foo.push(...myData.filter(item => item.id === foo[i].parentId));
}
console.log(foo);
只是 DB select 比 JS 代码中的 Array#filter() 更快更高效,但基本上它们产生相同的结果; (0 个或更多)匹配列表
这里显而易见的答案是用一个 class 表示对象,然后是对父对象的引用(如果有的话)。跨树的查询将从树的给定节点和 return 该节点的所有父对象开始。每个节点将只有一个直接父节点。
有没有更好的方法从计算上或从软件设计的角度来做到这一点?
编辑:寻找计算复杂性改进建议或可维护性建议。内存在这里不是一个大问题。
@Thomas a relational one. Not sure what our team's opinion is on stored procs but if there is compelling enough reason to use them I'm sure I can make the case.
在关系数据库中,我会使用 common-table-expression
WITH foo AS
(
-- your start node
SELECT *
FROM MyData AS d
WHERE d.id = 123
UNION ALL
-- traversing up
SELECT parent.*
FROM MyData AS parent
JOIN foo AS child
ON parent.id = child.parentId
)
-- selecting the data you want to return from the CTE
SELECT * FROM foo;
在 JS 术语中,这里描述上述查询的作用:
// initial SELECT
var foo = myData.filter(item => item.id === 123);
// UNION ALL + SELECT with JOIN onto `foo`
for (let i = 0; i < foo.length; ++i) {
foo.push(...myData.filter(item => item.id === foo[i].parentId));
}
console.log(foo);
只是 DB select 比 JS 代码中的 Array#filter() 更快更高效,但基本上它们产生相同的结果; (0 个或更多)匹配列表