Javascript 根据字段值从对象的平面数组生成层次树
需要转换数组,如:Javascript 根据字段值从对象的平面数组生成层次树,javascript,data-structures,Javascript,Data Structures,需要转换数组,如: [ {value: 'a', depth: 1, children: []}, {value: 'c', depth: 2, children: []}, {value: 'd', depth: 2, children: []}, {value: 'e', depth: 1, children: []}, {value: 'f', depth: 2, children: []}, {value: 'g', depth: 3, children: []}
[
{value: 'a', depth: 1, children: []},
{value: 'c', depth: 2, children: []},
{value: 'd', depth: 2, children: []},
{value: 'e', depth: 1, children: []},
{value: 'f', depth: 2, children: []},
{value: 'g', depth: 3, children: []},
{value: 'i', depth: 4, children: []},
// depth can bee any int but the integer row is respected
{value: 'j', depth: n, children: []},
// ...
{value: 'z', depth: 3, children: []},
]
进入:
非常感谢您的帮助
我知道我应该使用递归函数,但却停留在这里。不需要递归。您可以为标高使用辅助数组,并将深度作为基于零的值。此值需要调整 父子关系的选择基于顺序,因此每个子元素都跟随上一个深度元素的最后一个父元素 var数组=[{value:'a',depth:1,children:[]},{value:'c',depth:2,children:[]},{value:'e',depth:1,children:[]},{value:'f',deptren:2,children:[]},{value:'i',depth:4,children[]},{value:'z',deptren 3,children, 结果=[], 级别=[{children:result}]; array.forEacho=>levels[o.depth-1]。children.pushlevels[o.depth]=o; console.logresult;
.作为控制台包装器{max height:100%!important;top:0;}请添加卡住的位置。到目前为止您尝试了什么?请发布您的代码以及层次结构背后的逻辑。您将如何确定谁是谁的孩子?非常感谢Nina!你真是天才
[
{value: 'a', depth: 1, children: [
{value: 'c', depth: 2, children: null},
{value: 'd', depth: 2, children: null},
]},
{value: 'e', depth: 1, children: [
{value: 'f', depth: 2, children: [
{value: 'g', depth: 3, children: [
{value: 'i', depth: 4, children: [
{value: 'j', depth: n, children: [
// ...
]},
]},
]},
{value: '', depth: 3, children: null},
]},
]},
]