Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Mar 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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" : [
          {}
         ]
          }
         ] 
          }
         ]
          }
         ]
         }
        ] 
    }
    ]

  • #2
    Regular Coder hdewantara's Avatar
    Join Date
    Aug 2009
    Location
    Jakarta, Indonesia.
    Posts
    406
    Thanks
    9
    Thanked 60 Times in 59 Posts
    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;


  • #3
    Regular Coder
    Join Date
    Jan 2013
    Location
    Sunnyvale, CA
    Posts
    201
    Thanks
    11
    Thanked 10 Times in 10 Posts
    don't we just love elegant code!

    and don't forget to break when you retrieve the desired value.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •