js 一維數組轉換為樹形結構


測試數據:

const list = [
  { id: 1, pid: 0, name: '四川' },
  { id: 2, pid: 1, name: '成都' },
  { id: 3, pid: 1, name: '宜賓' },
  { id: 4, pid: 1, name: '綿陽' },
  { id: 5, pid: 1, name: '德陽' },
  { id: 6, pid: 2, name: '高新區' },
  { id: 7, pid: 2, name: '武侯區' },
  { id: 8, pid: 3, name: '翠屏區' }
];

方法一: 使用遞歸進行轉換. 傳入數組,根節點父級id,返回一個樹結構的數組.

const arrayToTree = (arr, pid) => {
  return arr.reduce((res, current) => {
    if (current['pid'] === pid) {
      current.children = arrayToTree(arr, current['id']);
      return res.concat(current);
    }
    return res;
  }, []);
};
console.log(arrayToTree(list, 0))

方法二:hash表 + 引用關系.傳入數組,根節點id ,返回一個樹結構對象

const arrayToTree = (arr, rootId) => {
  const map = {};
  for (const iterator of arr) {
    map[iterator['id']] = iterator;
  }
  for (const iterator of arr) {
    const key = iterator['pid'];
    if (!(key in map)) continue;
    map[key].children = (map[key].children || []).concat(iterator);
  }
  return map[rootId];
};
console.log(arrayToTree(list, 1));


免責聲明!

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



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