【问题标题】:JavaScript loop through depth array into a nested objectJavaScript 循环遍历深度数组进入嵌套对象
【发布时间】: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


【解决方案1】:

使用 Map 或字典(对象)检索父对象时,创建树会更容易。将整棵树缩减为 Map 后,检索包含整棵树的根。

const createItem = (type) => ({ type, children: [] })

const fn = (arr, root) => arr.reduce((acc, d) => {  
  const parent = d - 1
  
  const item = createItem(d)
  
  if(d !== root && !acc.has(parent)) acc.set(parent, createItem(parent))
  
  if(d !== root) acc.get(parent).children.push(item)
  
  return acc.set(d, item);
}, new Map()).get(root);

const depth = [0, 1, 2, 3, 3, 2, 3, 3, 3 ]

const result = fn(depth, 0)

console.log(result)

【讨论】:

  • 感谢您的回答——这绝对让我对如何解决这个问题有了另一种看法!
【解决方案2】:

当您按预定顺序获取数据时,您实际上并不需要地图:

function convert(data) {
    let i = 0;
    
    function getChildren(type) {
        let children = [];
        while (data[i] === type) {
            i++;
            children.push({
                type,
                children: getChildren(type + 1)
            });
        }
        return children;
    }
    
    return getChildren(0);
}

let data = [0, 1, 2, 3, 3, 2, 3, 3, 3];
console.log(convert(data));

【讨论】:

  • 谢谢你的回答,这解决了我的问题,我认为我的用例是最好的答案!
猜你喜欢
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
相关资源
最近更新 更多