How to find the parent name from child using lodash and print the path

You could take an object with all nodes and id as key and get all parents until no id is available.

const
    getParents = (array, id) => {
        const
            nodes = array.reduce((r, o) => (r[o.id] = o, r), {}),
            getP = id => id in nodes
                ? [...getP(nodes[id].parent_id), nodes[id].class_name]
                : [];
        return getP(id).join('/');
    },
    array = [{ id: 1, class_name: 'Home', parent_id: 0 }, { id: 2, class_name: 'Folder1', parent_id: 1 }, { id: 3, class_name: 'Folder2', parent_id: 1 }, { id: 4, class_name: 'SubFolder1', parent_id: 2 }, { id: 5, class_name: 'EndFolder1', parent_id: 4 }];

console.log(getParents(array, 4));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top