扁平数组变为树结构
假设不考虑其他,只需要按照现有的数组索引把后续的元素绑定到前面一个元素的children属性数组中。
场景为:级联控件 。
输入 let children = [{value:12,key:12},{value:23,key:45}] 输出 let options = [ {value:12, key:12, children:[ {value:12, key:12, children:[{ value:12, key:12,
}]
} ] }]
代码如下 :
transOption = (item, children, index) => {
const len = children.length;
let Newitem = {
...item
isLeaf: index === len - 1,
};
if (index + 1 === len) {
return Newitem
}
Newitem.children =
return {
...Newitem,
children : [this.transOption(children[index + 1], children, index + 1)]
}
}