// 將普通數組轉換為tree數組 export function transData (a, idStr, pidStr, chindrenStr) { const r = [] const hash = {} const id = idStr const pid = pidStr const children = chindrenStr let i = 0 let j = 0 const len = a.length for (; i < len; i++) { hash[a[i][id]] = a[i] } for (; j < len; j++) { const aVal = a[j] const hashVP = hash[aVal[pid]] if (hashVP) { !hashVP[children] && (hashVP[children] = []) hashVP[children].push(aVal) } else { r.push(aVal) } } return r }
使用例子:
this.navDataList:
this.navList = transData(JSON.parse(JSON.stringify(this.navDataList)), 'id', 'parentId', 'children')
第一個參數是要轉換的數組,要轉變為json字符串
第二個參數是數組里的id,用來區別每個元素
第三個參數是元素對應的父元素的id值
第四個參數是父元素中子元素的名稱