【发布时间】:2019-06-26 19:27:26
【问题描述】:
我目前有一个 Javascript 对象数组,如下所示:
myArray = [
{
id: 'top-id1',
title: 'title1',
subElements: [
{
id: 'id2',
title: 'title2',
subElements: [
{
id: 'id3',
title: 'title2',
subElements: [
...
]
}
]
},
{
id: 'id4',
title: 'title4',
},
...
]
},
{
id: 'top-id5',
title: 'title5',
subElements: [
...
]
},
...
];
这个数组在技术上可以无限长和无限深(通过子元素),但实际上它在顶层最多只有 4 个对象,并且最大深度为 4 级,因此性能和运行时不是一个大问题。
我要查找的内容: 给定任何 id,我需要返回包含第一个 id 的顶级对象的 id。因此,如果我得到“id3”,我需要返回“top-id1”。如果我得到'top-id5',我还需要返回'top-id5'。重要的是,这是在 React 应用程序的上下文中。有人可以帮我找出一个算法吗?
【问题讨论】:
-
DFS/BFS“树遍历”类型的搜索算法将是您正在寻找的,具体取决于您想要返回的结果。您可能想要 DFS(深度优先搜索)。
-
这不完全是重复的,但stackoverflow.com/q/56066101 的答案可能会帮助你。
标签: javascript reactjs