问题抛出:
接口返回如下的数据,现在用element-ui的cascader组件做一个树形结构的下拉展示
const arr = [
{
kind: '百度1'
},
{
kind: 'google',
children: [
{
kind: '小王'
}
]
},
{
kind: '小王'
},
{
kind: '王五',
children: [
{
kind: '李四',
children: [
{
kind: '李思思'
}
]
}
]
}
]
现在需要的数据结构形如:不知道具体层级多少。
let data = [
{
label: '张三'
},
{
label: '李四',
children: [{ label: '李思思' }]
},
{
label: '张三',
children: [
{
lable: '张三三',
children: [
{
label: '张三三三'
}
]
}
]
}
]
参考了网上很多方法,都不能满足我的需求,特研究了下,本人亲测方法:
function render(treeJson) {
if (!Array.isArray(treeJson) || treeJson.length <= 0) {
return ''
}
let res = []
treeJson.forEach(function(item, i) {
res.push({
label: item.kind,
children: item.children ? render(item.children) : ''
})
if (Array.isArray(item.children) && item.children.length > 0) {
Object.assign(...res, { children: render(item.children) })
} else {
Object.assign(...res)
}
})
return res
}
console.log(render(arr))
不对的地方,请多指教!
每天朝九晚五的码农,进步一点是有点