/** * @description 一维数组转树形数据 * */ export const arrToTree = (data = [], conf = {}) => (((data, { id = 'id', parentId = 'parentId', children = 'children' }) => { let result = [] if (!Array.isArray(data)) { return result } data = commonMerge({}, { list: data }).list data.forEach(item => { delete item[children] }) let map = {} data.forEach(item => { map[item[id]] = item // id为键,原数据每一项为值的map对象 }) data.forEach(item => { let parent = map[item[parentId]] // item的parentId若与map对象的键相同,则item为父级节点 if (parent) { (parent[children] || (parent[children] = [])).push(item) } else { result.push(item) } }) return result })(data, conf));
参考:https://www.jb51.net/javascript/2876872tm.htm 标签:map,JavaScript,id,item,result,一维,树型,data,children From: https://www.cnblogs.com/hello-world-01/p/17787573.html