最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting Parent node from Json object with Jquery - Stack Overflow

programmeradmin0浏览0评论

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 /

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/jftrg9ko/

Share Improve this question edited Aug 28, 2014 at 6:29 AddyProg asked Aug 28, 2014 at 6:21 AddyProgAddyProg 3,05014 gold badges63 silver badges114 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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)

  1. 暂无评论