Getting Parent node from Json object with Jquery

前端 未结 2 1365
慢半拍i
慢半拍i 2021-01-03 01:04

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
           


        
相关标签:
2条回答
  • 2021-01-03 01:33

    To get all ocuurences

    var pars,k,v,chk;
        pars = [];
        $.each(json,function(k,v){
            chk = k;
            $.each(v,function(k,v)
                if(k === node){
                    pars.push(chk);
                }
            })
        })
    
    0 讨论(0)
  • 2021-01-03 01:34

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题