【发布时间】:2019-09-05 14:06:22
【问题描述】:
我有一个像下面这样的对象:
[
{
"uid": "aaa-aaa",
"name": "foo",
"children": []
},
{
"uid": "aaa-bbb",
"name": "bar",
"children": [
{
"uid": "aaa-bbc",
"name": "baz",
"children": []
},
{
"uid": "aaa-ccc",
"name": "fooz",
"children": [
{
"uid": "aaa-bcb",
"name": "Yeah !",
"children": []
}
]
}
]
}
]
我正在尝试编写一个函数,该函数将该对象以uid 作为参数,并返回指向该对象中带有uid 的元素的路径(如果未找到,则返回null)。
类似这样的:
> getElementPath(bigObject, 'aaa-bcb')
[1, "children", 1, "children", 0]
or
> getElementPath(bigObject, 'aaa-bcb')
[1, 1, 0]
我知道函数必须是递归的,因为嵌套级别应该没有限制。我已经尝试过了,但它总是返回 null :
function getElementPath (haystack, uid, currentPath = []) {
if (haystack.uid === uid) {
return currentPath
}
if (Array.isArray(haystack.children)) {
for (let i = 0; i < haystack.children.length; i++) {
let newPath = [...currentPath, i]
let path = getElementPath(haystack.children[i], uid, newPath)
if (path !== null) {
return path
}
}
}
return null
}
【问题讨论】:
-
如果您必须经常使用这个
getElementPath()函数,将数组缩减为一个对象一次是有意义的,这样您就可以直接访问任何元素。这可能会完全消除拥有完整路径的需要。 -
您的“跟随对象”是一个数组。该数组作为
haystack传递给函数getElementPath,然后在第一个条件haystack.uid === uid中haystack是一个数组,而在下一个条件下haystack.children出于同样的原因未定义。剩下的唯一一个return语句最终返回 null。 ¯_(ツ)_/¯
标签: javascript json search