开发者

Searching in a multidimensional json object

I thought this was going to be easy, but it's turning into quite a headache. I have a multidimensional JSON object being returned from my webserver. I'm parsing it to build a fairly deep navigation pane. I need to be able to search this object, but I'm coming up blank for the means.

The object is structured as so: tree->rows[]=>tree->rows[]=>tree …

Each tree can have many rows, and each row can have a tree etc.

At the row level there are a few variables, I need to search and find the value of one. EX: if(tree.rows[x].tree.rows[y].url =="http://stackoverflow.com" return true;

My difficulty is, I don't know how to traverse the whole object. Even if I do it recursively I don't know how I could keep going up and down all the rows.

Here's an example of the object:

var jsonLNav = {itemClassName:"NodeLink",linkClassName:"NodeLinkTitle",linkHideClassName:"HideFromProd",navCategoryClassName:"NavCategory",onLoadJS:"",tree:[{pos:1,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"1",rows:[{hide:0,title:开发者_StackOverflow中文版"More IT Help",isNC:0,isMig:0,url:"http://vm-hsspdv-d09p/en-us/Help/Pages/ITHelp.aspx",isOL:0,tree:{pos:2,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"3"}},{hide:0,title:"Office 2010",isNC:0,isMig:1,url:"http://office2010.lmig.com/Pages/Default.aspx",isOL:0,tree:{pos:2,wid:"263a97c2-7cb9-470c-bf86-cadc28ae1323",pid:"9"}},{hide:0,title:"E-mail Management",isNC:0,isMig:0,url:"http://vm-hsspdv-d09p/en-us/Help/EmailManagement/Pages/default.aspx",isOL:0,tree:{pos:2,wid:"8be66348-8da1-4e5c-90c5-0930d2f52d1a",pid:"123"}},]}]}; 

This example piece doesn't have any child trees of the row, the object that does is tens of thousands characters long, I can post if necessary.

The best code I can think of would be close to this (not tested, conceptually I'm missing something):

function findURL(url)
{

alert(searchJson(jsonLNav.tree[0],url));
}//end findURL

function searchJson(tree,url)
{

for(var x=0; x<=tree.rows.length-1;x++)
{
    if(url == tree.rows[x].url)
    {
        return tree.rows[x].title;
    }//end if
    else
    {
        searchJson( tree.rows[x].tree,url)
    }//end else
}//end for


}//end searchJson

Thanks!


When your search function calls itself recursively, it has to pay attention to the returned value, and somehow determine whether it's found it or not. Your function doesn't do anything special when it finds nothing, which I suppose is OK because the return value will be undefined.

else
{
    var t = searchJson( tree.rows[x].tree,url);
    if (t) return t;
}//end else

That way, the first loop that finds the url will return the (hopefully non-empty) "title", and that will propagate up the stack as a non-empty value for all the "if (t)" statements on the call stack.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜