Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

js怎么将二维数组转换为树形结构?

image.png
这是我的写法:

function arrToTree (arr, index = '', parentName) {
  let tree = []
  console.log(parentName);
  let temp
  for (let i = 0; i < arr.length; i++) {
    console.log(temp);
    let obj = {}
    if (parentName && parentName == temp) {
      let index = obj.id
      let newArr = arr[i].slice(1)
      obj.child.push(arrToTree(newArr, index, arr[i][0]))
    } else {
      if (!Array.isArray(arr[i])) {
        obj = {
          "id": `${index}0${i + 1}`,
          "name": arr[i],
        }
      } else {
        obj = {
          "id": `${index}0${i + 1}`,
          "name": arr[i][0],
        }
      }
      temp = obj.name
      if (Array.isArray(arr[i]) && arr[i].length > 1) {
        let index = obj.id
        let newArr = []
        newArr = arr[i].slice(1)
        obj.child = (arrToTree(newArr, index, arr[i][0]))
      }
    }

    tree.push(obj)
  }
  return tree
}

let arr = [["hello", "bill"], ["hello", 'jack'], ["world", "foo", "jerry"], ["world", "foo", "peter", "tom"], ["world", "bar"]]
console.log(JSON.stringify(arrToTree(arr)));

写到这一步不知道,改怎么写了,主要是parentName和temp那一块有问题,求大佬指教


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function c (arr) {
    var ids = [],
        result = [],
        randomKey = Math.random().toString(32).slice(-8),
        map = new Map();

    function createItem (name, index) {

        ids.length = index + 1;

        ids[index] = (ids[index] || 0) + 1;

        let cl = ids.slice(0, index + 1).map(k => String(k).padStart(2, '0')).join('');

        return {
            name,
            id: cl
        };
    }

    function add(list) {
        let base,
            vk = [];

        list.forEach((o, i) => {
            vk.push(o);

            let d = vk.join(randomKey),
                mo;

            if (!map.has(d)) {
                mo = createItem(o, i);
                map.set(d, mo);
                if (base) {
                    base.child = (base.child || []).concat(mo);
                } else {
                    result.push(mo);
                }
            } else {
                mo = map.get(d);
            }

            base = mo;
        });
    }

    arr.forEach(k => add(k));

    return result;
}

var t = [['hello','bil'],['hello','jack'],['world','foo','jerry'],['world','foo','peter','tom'],['world','bar']];

var result = c(t);

JSON.stringify(result, null, 4);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...