当前位置:网站首页>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属性
边栏推荐
- Where are the laravel framework log files stored? How to use it?
- 【Mysql】认识Mysql重要架构(一)
- Elastic APM安装和使用
- 您的登录IP不在管理员配置的登录掩码范围内
- 李沐d2l(六)---模型选择
- STM32+MFRC522完成IC卡号读取、密码修改、数据读写
- 大二上第五周学习笔记
- “could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32” 问题处理
- What are CSDN spaces represented by
- The Child and Binary Tree-多项式开根求逆
猜你喜欢

2022年上海市安全员C证考试试题及模拟考试

ZXing简化版,转载

Sending and receiving of C serialport

Elastic APM安装和使用

Does volatile rely on the MESI protocol to solve the visibility problem? (next)

NTT(快速数论变换)多项式求逆 一千五百字解析

2022 chemical automation control instrument operation certificate test question simulation test platform operation

CF1481C Fence Painting

原根与NTT 五千字详解

【Mysql】认识Mysql重要架构(一)
随机推荐
What are CSDN spaces represented by
Qt | 关于如何使用事件过滤器 eventFilter
Li Mu D2L (IV) -- softmax regression
Local cache
Server memory failure prediction can actually do this!
838. Heap sorting
838. 堆排序
CF1481C Fence Painting
Li Mu D2L (VI) -- model selection
Where are the laravel framework log files stored? How to use it?
js在控制台输出菱形
什么是异步操作
暑假第四周
JVM触发minor gc的条件
QT | about how to use EventFilter
2022流动式起重机司机考试题模拟考试题库模拟考试平台操作
Object type collections are de duplicated according to the value of an attribute
MySQL transaction
JS closure: binding of functions to their lexical environment
arcgis的基本使用1