直接上代码react
树形结构转扁平 数组
react中: flag=(arr)=> { let result = [] let item for (item of arr) { var res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据做为第一层级的填充 delete res['children'] result.push(res) if (item.children instanceof Array && item.children.length > 0) { // 若是当前child为数组而且长度大于0,才可进入flag()方法 result = result.concat(this.flag(item.children)) } } return result } getData=(arr, type = 'children') =>{ arr.forEach((res) => { var resType = JSON.parse(JSON.stringify(res)) // 先克隆一份数据做为第一层级的填充 delete resType[type] array.push(resType) if (Array.isArray(res[type]) && res[type].length > 0) { // 若是当前child为数组而且长度大于0,才可进入flag()方法 this.getData(res[type]) } }) return array } render中: console.table(this.flag(menusTree));//menusTree为树形结构 console.table(this.getData(menusTree)); ///////////////////////////////////////////////////////////////////////////// 普通js: function flag(arr) { let result = [] for (item of arr) { var res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据做为第一层级的填充 delete res['children'] result.push(res) if (item.children instanceof Array && item.children.length > 0) { // 若是当前child为数组而且长度大于0,才可进入flag()方法 result = result.concat(flag(item.children)) } } return result } console.log(flag(ss)); var array = [] function getData(arr, type = 'children') { arr.forEach((res) => { var resType = JSON.parse(JSON.stringify(res)) // 先克隆一份数据做为第一层级的填充 delete resType[type] array.push(resType) if (Array.isArray(res[type]) && res[type].length > 0) { // 若是当前child为数组而且长度大于0,才可进入flag()方法 getData(res[type]) } }) return array } console.log(getData(ss))
扁平转树形this
普通js: function treeData(source, id, parentId, children) { let cloneData = JSON.parse(JSON.stringify(source)) return cloneData.filter(father => { let branchArr = cloneData.filter(child => father[id] == child[parentId]); branchArr.length > 0 ? father[children] = branchArr : '' return father[parentId] == 0 // 若是第一层不是parentId=0,请自行修改 }) } let ss = treeData(arr, 'id', 'parentId', 'children') console.log(ss); arr为扁平结构