Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Parent node from Json object with Jquery

I am trying to get parent node in json object by child it The json i am getting from client is a multilevel directory hierarchy the hierarchy is like

Root
   -
   -Folder-1
           -folder1(a)
           -folder1(b)
   -folder-2
   -folder-3
           -folder3(a)

what i want is, when I put folder3(a)'s id it should give me folder-3's id and name

Here is the fiddle with actual json object http://jsfiddle.net/jftrg9ko/

like image 860
Addy Avatar asked Aug 28 '14 06:08

Addy


1 Answers

You have to search through the tree anyway so just remember the parent and return that if you found the right child.

I fiddled something: http://jsfiddle.net/jftrg9ko/1/

function getParent(tree, childNode)
{
    var i, res;
    if (!tree || !tree.folder) {
        return null;
    }
    if( Object.prototype.toString.call(tree.folder) === '[object Array]' ) {
        for (i in tree.folder) {
            if (tree.folder[i].id === childNode) {
                return tree;
            }
            res = getParent(tree.folder[i], childNode);
            if (res) {
                return res;
            }
        }
        return null;
    } else {
        if (tree.folder.id === childNode) {
            return tree;
        }
        return getParent(tree.folder, childNode);
    }
}
like image 121
mahe Avatar answered Oct 21 '22 13:10

mahe