samedi 9 mai 2015

Need help iterating through a complex Json (no jquery)

I need to create a symfony2 bundle that generates a sidebar from a YAML file

I created this YAML structure

Sidebar:
  - Frontpage:
        - Dashboard:
            _icon: 'icon-home'
            _route: 'link'
  - Actions:
          - My_Likes:
              _icon: 'icon-dislike'
              _route: 'link'
          - My_Dislikes:
              _icon: 'icon-home'
              _route: 'link'
  - Interests:
          - Add_Interest:
              _icon: 'icon-home'
              _route: 'link'

which returns this JSON as a response.

{
  "Sidebar": [
    {
      "Frontpage": [
        {
          "Dashboard": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Actions": [
        {
          "My_Likes": {
            "_icon": "icon-dislike",
            "_route": "link"
          }
        },
        {
          "My_Dislikes": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Interests": [
        {
          "Add_Interest": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    }
  ]
}

Using ajax, the json is returned on the 'data' variable on the client side

Sidebar.model.request(function(data)
{ 
    for(var a=0; a< data.Sidebar.length; a++ )
    {
       console.log(data.Sidebar[a]);
    }
});

I need to find a way to iterate through the parents and find the corresponding children. I only need help creating the for loop, so a solution using console.log(data[stuff]); would be enough


EDIT: here is the adjusted snippet of Daniel Rosano's code

    Sidebar.model.request(function(data)
    { 
        //Get Sidebar items
        var SidebarItems = data.Sidebar;

        //Find Categories in Sidebar Items
        for(var a=0; a< SidebarItems.length; a++ )
        {
            var category = SidebarItems[a];

            //Get Category name and append it to sidebar
            var category_name = getSubitemName(category);
            Sidebar.view.renderCategory(category_name);

            //find subitems in categories
            for(var b=0; b < category[category_name].length; b++)
            {
                var button = category[category_name][b];
                var button_name = getSubitemName(button);

                var button_attributes = button[button_name];

                console.log(button_attributes['_icon']);
                Sidebar.view.renderButton(button_name);
            }
        }

        function getSubitemName(parent)
        {
            for(child in parent)
            {
                return child.toString();
            }
        }
    });

this is the result, thanks Daniel

Obviously incomplete but this is the result

Aucun commentaire:

Enregistrer un commentaire