function treeList (array = [], prop = '') {
if (!Array.isArray(array)) throw Error(`${array} is not array`)
if (prop.constructor.name !== 'String') throw Error(`${prop} is not string`)
let list = []
const data = array.reduce((obj, pre) => {
if (!pre.hasOwnProperty(prop)) throw Error(`${prop} is not found`)
const key = pre[prop]
if (!obj[key]) {
obj[key] = []
}
obj[key].push(pre)
return obj
}, {})
for (let key in data) {
list.push({ [prop]: key, children: data[key] })
}
return list
}
普通数据结构转树形数据结构
最新推荐文章于 2023-03-02 15:21:46 发布