var mapObj = {
value: 'code',
label: 'name',
children: 'list'
}; // 级联要求的数据格式
var treeObj = [
{
code: 'beijing',
name: '北京',
list: [
{
code: 'tiantan',
name: '天坛',
list:[]
}
]
}
]; // 回台返回的数据格式
console.log(converTree(treeObj,mapObj)
function converTree (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let value = item[ map.value ];
let label = item[ map.label ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = converTree(children, map);
}
result.push({ value, label, children });
})
return result
}
网友评论