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

Viewed 406

I am having a collection like below

const tree = [
    {
        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
    }
]

In this collection, i know the child class_name as SubFolder1 with id 4 and parent_id 2 from this parent id i need to traverse back to the root node to find the path below.The parent id act as id for each object.

SubFolder1
Folder1/SubFolder1
Home/Folder1/SubFolder1

I have tried with lodash find which stops in one level i need to traverse to the root that it when the parent_id is 0. and add the path.

 if (temp.parent_id !== '0') {
    temp = find(tree, {id: temp.parent_id});
 } else {
    tempClassName = `${temp.class_name}`;
 }
1 Answers

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));

Related