Go Back   CodingForums.com > :: Client side development > JavaScript programming > DOM and JSON scripting

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-12-2013, 11:25 AM   PM User | #1
pallavi1811
New to the CF scene

 
Join Date: Mar 2013
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
pallavi1811 is an unknown quantity at this point
Urgent help: need to write a recursive func to access nested json

hi..

in the below json i need to get the value of the id==8, using some recursive function. Please reply asap


Code:
{
    "id" : 1,
    "name" : "a",
    "children" : [
     {
     "id" : 2,
     "name" : "b",
     "children" : [
      {
      "id" : 3,
     "name" : "c",
     "children" : [
      {
      "id" : 4,
     "name" : "d",
     "children" : [
      {
      "id" : 5,
     "name" : "e",
     "children" : [
      {}
     ]
      }
     ] 
      }
     ]
      }
     ]
     }
    ] 
},
{
    "id" : 6,
    "name" : "f",
    "children" : [
     {
     "id" : 7,
     "name" : "g",
     "children" : [
      {
      "id" : 8,
     "name" : "h",
     "children" : [
      {
      "id" : 9,
     "name" : "i",
     "children" : [
      {
      "id" : 10,
     "name" : "j",
     "children" : [
      {}
     ]
      }
     ] 
      }
     ]
      }
     ]
     }
    ] 
}
]
pallavi1811 is offline   Reply With Quote
Old 03-13-2013, 07:25 PM   PM User | #2
hdewantara
Regular Coder

 
hdewantara's Avatar
 
Join Date: Aug 2009
Location: Jakarta, Indonesia.
Posts: 287
Thanks: 4
Thanked 39 Times in 39 Posts
hdewantara is an unknown quantity at this point
To enlist all the records:
PHP Code:
function walk(arr){
    var 
str '';
    for (var 
0arr.lengthi++)
        if (
arr[i].id){
            
str += arr[i].id ':' arr[i].name '\n';
            if (
arr[i].children.length 0)
                
str += walk(arr[i].children);
        }
    return 
str;

hdewantara is offline   Reply With Quote
Old 03-14-2013, 06:04 AM   PM User | #3
sbhmf
New Coder

 
Join Date: Jan 2013
Location: Sunnyvale, CA
Posts: 40
Thanks: 3
Thanked 1 Time in 1 Post
sbhmf is an unknown quantity at this point
don't we just love elegant code!

and don't forget to break when you retrieve the desired value.
sbhmf is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:38 AM.


Advertisement
Log in to turn off these ads.