服务器返回的数据:
{
"code": 1000,
"msg": "操作成功!",
"data": [
{
"callReasonNumber": "10",
"callReason": "创伤",
"list": [
{
"callReasonNumber": "1001",
"callReason": "交通伤",
"list": []
},
{
"callReasonNumber": "1002",
"callReason": "钝器伤",
"list": []
}
]
},
{
"callReasonNumber": "11",
"callReason": "非创伤",
"list": [
{
"callReasonNumber": "1101",
"callReason": "昏迷/晕厥",
"list": []
},
{
"callReasonNumber": "1102",
"callReason": "头痛",
"list": []
},
]
}
需要展示数据的形式:
const targetData = [
{
value: 'zhinan',
label: '指南',
children: [
{
value: 'shejiyuanze',
label: '设计原则',
children: [
{
value: 'yizhi',
label: '一致'
},
{
value: 'fankui',
label: '反馈'
},
{
value: 'xiaolv',
label: '效率'
},
{
value: 'kekong',
label: '可控'
}
]
}
]
}
];
代码
要递归遍历一个嵌套的对象数组结构,直到 list 属性为空数组,使用递归函数来实现。
当list为空时,chindren属性存在,且为undefined:
transformData (data) {
return data.map(item => ({
value: item.callReasonNumber,
label: item.callReason,
children: item.list.length > 0 ? this.transformData(item.list) : undefined
}));
},
当list为空时,children属性不存在:
transformData (data) {
return data.map(item => ({
value: item.callReasonNumber,
label: item.callReason,
...(item.list.length > 0 && { children: this.transformData(item.list) })
}));
},
- 如果条件表达式返回的是一个对象{ children: this.transformData(item.list) },则展开该对象并将 children 属性添加到目标对象中。
- 如果条件表达式返回 false,则什么也不添加。