直接上码
<script>
// 树结构
const options = [
{
value: 'Shenzhen',
label: '深圳',
children: [
{
value: 'Longgang',
label: '龙岗区',
children: [
{
value: 'Bantian',
label: '坂田街道',
},
],
},
],
},
{
value: 'Guangzhou',
label: '广州',
children: [
{
value: 'Panyu',
label: '番禺区',
children: [
{
value: 'Qiaonan',
label: '桥南街道',
},
],
},
],
},
];
// 递归函数
const Fn = data => {
// 使用forEach遍历,添加新的属性
// data.forEach((item, i) => {
// if (item.children) {
// // 调用递归函数
// Fn(item.children)
// }
// data[i].key = data[i].value
// })
// 使用map遍历,生成新的数组
data = data.map(item => {
return {
// ...item, // 如果想在原数组添加属性
name: item.label,
id: item.value,
children: item.children ? Fn(item.children) : item.children // 判断当前是否还有子节点
}
})
return data
}
// 调用
console.log(Fn(options));
</script>