当前位置:网站首页>js中树与数组的相互转化(树的子节点若为空隐藏children字段)
js中树与数组的相互转化(树的子节点若为空隐藏children字段)
2022-07-26 09:21:00 【周小盗】
写博客是为了记笔记
前言
在使用elmentUI
或者antUI
等中的 cascader
级联选择器时 ,需要树级结构,有时就会需要进行树与数组的相互转换,这里的树与数组的转化将子children为空时省去了,避免出现选择时空白页的情况(如图一)
一、树转数组
treeToArray(list, newArr = []) {
list.forEach(item => {
const {
children} = item
if (children) {
delete item.children
if (children.length) {
newArr.push(item)
return this.treeToArray(children, newArr)
}
}
newArr.push(item)
})
return newArr
}
二、数组转树
listToTree(list, parentId = null) {
return list.filter(item => item.parentId === parentId).map(item => {
let children= this.listToTree(list, item.id)
if (children.length > 0) {
return {
...item,
children
}
} else {
return {
...item
}
}
})
}
三、使用
1.data中定义的数据(树)options
options: [
{
value: 'zhinan',
label: '指南',
parentId:'0',
id: "aa",
children: [
{
value: 'shejiyuanze',
label: '设计原则',
parentId:'aa',
id: "aa01",
children: [
{
value: 'yizhi',
label: '一致',
parentId:'aa01',
id: "aa0101",
},
{
value: 'fankui',
label: '反馈',
parentId:'aa01',
id: "aa0102",
},
]
},
]
},
{
value: 'zujian',
label: '组件',
parentId:'0',
id: "bb",
children: [
{
value: 'basic',
label: 'Basic',
parentId:'bb',
id: "bb01",
children: [
{
value: 'layout',
label: 'Layout 布局',
parentId:'bb01',
id: "bb0101",
},
]
},
{
value: 'form',
label: 'Form',
parentId:'bb',
id: "bb02",
children: []
},
]
},
],
2.使用树转数组(注意转成数组时默认删除children
属性)
let list = this.treeToArray(this.options)
console.log("list",list)
2.使用数组转树
let tree = this.listToTree(list,list[0].parentId)
console.log("tree",tree)
注意这里当children
为[]
时,默认不挂载children
属性
边栏推荐
猜你喜欢
随机推荐
arc-gis的基本使用2
Go intelligent robot alpha dog, alpha dog robot go
【线上死锁分析】由index_merge引发的死锁事件
堆外内存的使用
ext4文件系统打开了DIR_NLINK特性后,link_count超过65000的后使用link_count=1来表示数量不可知
Elastic APM安装和使用
2022 tea artist (intermediate) special operation certificate examination question bank simulated examination platform operation
安卓 实现缓存机制,多种数据类型缓存
839. 模拟堆
Error: cannot find module 'UMI' problem handling
The essence of attack and defense strategy behind the noun of network security
838. Heap sorting
Vertical search
吴恩达机器学习之线性回归
分布式跟踪系统选型与实践
李沐d2l(五)---多层感知机
OFDM 十六讲- OFDM
2022 mobile crane driver test question simulation test question bank simulation test platform operation
大二上第一周学习笔记
redis原理和使用-安装和分布式配置