返回多维数组特定id的层级

193 阅读1分钟

存在类似以下树形结构的tree,每个id都是独一无二,设计一个函数,参数是tree和id,返回结果是这个id的层级。

举例:结构如[{id:1,children:[{id:2}]},{id:3}],输入这个结构和2,返回字符串"0-0"。

function treeId(arr, id) {
    var res = '';

    function ttI (arr, id, idIndex) {
        var steps = '';
        arr.forEach((item, index) => {
            steps = idIndex !== null ? idIndex + '-' + index : index;
            if (item.id === id) {
                res = steps;
                return;
            } else if (item.children && item.children instanceof Array) {
                steps = ttI(item.children, id, steps);
            }
        })  
    }
    
    ttI(arr, id, null);
    
    return res;
}