Modifying a tree structured object

Hi !
I have this function :

const insertRecordByPath = (rootFolder, newFolder, parentPath) => {
    if(parentPath[parentPath.length - 1] !== '/'){
        console.log('not a directory');
        return null;
    }
    let pathSegments = parentPath.split('/');
    let currentFolder = rootFolder;
    pathSegments = pathSegments.slice(1);
    pathSegments.forEach((name, index) => {
        let childFolder = currentFolder.children.find((child) => child.name === name);
        if (childFolder) {
            currentFolder = childFolder;
            if(index === pathSegments.length - 1){
                let newChild = new Folder(newFolder);
                currentFolder.children.push(newChild);
                currentFolder = newChild;
            }
        };
    });
    const arr = currentFolder.children.filter((child) => child.name === newFolder.name);
    if(arr.length > 1){
        console.log('folder already exists');
        return null;
    }
    console.log('rootFolder', JSON.stringify(rootFolder, null, 2));
    // return the updated root folder
    return rootFolder;

};

and I’m trying to add a new folder to an existing parent folder, the depth is unknown , and the return however is rootFolder unchanged.
what am I doing wrong here ?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.