將普通數組轉換為tree數組


// 將普通數組轉換為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值

第四個參數是父元素中子元素的名稱

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM