【发布时间】:2021-11-05 13:38:53
【问题描述】:
我在将深度列表转换为嵌套对象时遇到了一些问题。
例如,我有一个这样的列表:
"depth": [ 0, 1, 2, 3, 3, 2, 3, 3, 3 ],
我需要想出一个递归函数来生成这样的对象:
"depth": [
{
"type": 0,
"children": [
{
"type": 1,
"children": [
{
"type": 2,
"children":[
{ "type": 3, "children": []},
{ "type": 3, "children": []},
]
},
{
"type:": 2,
"children":[
{ "type": 3, "children": []},
{ "type": 3, "children": []},
{ "type": 3, "children": []},
]
}
]
}
]
}
]
}
所以这里的规则是,较低的数字是父母,较高的数字是前一个较低数字的兄弟姐妹。
到目前为止,我想出的是:
const depth = [0, 1, 2, 3, 3, 2, 3, 3, 3]
// Start looping through all the numbers in the depth
for (let i = 0; i < depth.length; i++) { //depth.length
// As i loop i want to only look at the array i have explored
// So that i can find the parent that is 1 lower in the array
let getParent = depth.slice(0, i).lastIndexOf(depth[i] - 1) // position of last lower array
// Here i check if the current depth item is bigger than the currently lower Item in the array
if (depth[i] > depth[getParent]) {
console.log(depth[i] + " Nesting into " + depth[getParent]) // Is child of that item
}
}
我认为这成功地将孩子映射到父母。但现在我被困在产生我想要的结果的方法上。
如果有人有建议,我将不胜感激。
谢谢
【问题讨论】:
-
输入数组是否已排序?到目前为止,您在递归方面尝试过什么?
-
是的,深度变量已排序。我尝试了几种递归方法都没有成功,但我花了很多时间让它工作,并且很好奇是否有人解决了类似的问题
标签: javascript arrays object recursion nested