Find all the parent nodes in the tree given id

const data = [{
    id: 1,
    children: [{
        id: 2,
        children: [{
            id: 3,
        }, {
            id: 4,
        }],
    }],
}, {
    id: 5,
    children: [{
        id: 6,
    }],
}];

let nodes = [];
function getParentNodes(id, tree) {
    _getParentNodes([], id, tree);
    return nodes;
}

function _getParentNodes(his, targetId, tree) {
    tree.some((list) => {
        const children = list.children || [];
        if (list.id === targetId) {
            nodes = his;
            return true;
        } else if (children.length > 0) {
            const history = [...his];
            history.push(list);
            return _getParentNodes(history, targetId, children);
        }
    })
}

  To find the id specified node tree is very simple. If you want to find all the parent nodes specified change if the idea is to traverse the depth of each order are recorded, until you find the node id of the specified time, the output of this record.

  It only needs during each iteration, the previous record pass in the past can be.

Guess you like

Origin www.cnblogs.com/youyouluo/p/11546462.html