Starboy
Starboy

Reputation: 1635

Mootools JSON (Pulling Childs, of Childeren)

Accomplished pulling data from JSON, but having problems trying to pull additional information from child elements (ie: Sub Item 1, 2, etc) while in a loop.

http://jsfiddle.net/VVAFM/7/

{
    "title": "Main Title",
"items": [
    {
        "title": "Sub Title 1 "
    },
    {
        "title": "Sub Title 2",
        "items": [
            {
                "title": "Sub Item 1" //CAN'T GET MY HANDS ON THESE ITEMS!!!!!
            },
            {
                "title": "Sub Item 2"
            }
        ]
    },
    {
        "title": "Sub Title 3",
        "items": [
            {
                "title": "Sub Item 1"
            },
            {
                "title": "Sub Item 2"
            }
        ]
    },
    {
        "title": "Sub Title 4 "
    }
]
}

Here is my attempt to try to pull the "SubItems" into another ul within the already created li.

    var addItemsLi = function(itemsLi){
        itemsLi.each(function(itemLi){
            var el = new Element('li'),
                name = new Element('a', {'html': itemLi.title}).inject(el);

            if (itemLi.items){
                  var ul = new Element('ul'),
                      li = new Element('li').inject(ul),
                      subItem = new Element('a', {'html': itemLi.items.title}).inject(li);
            };

                el.inject(gallery);
        });
    };

Upvotes: 1

Views: 239

Answers (2)

Naftali
Naftali

Reputation: 146310

Here is a working fiddle: http://jsfiddle.net/maniator/VVAFM/11/

You forgot to loop through the items array:

var addItemsLi = function(itemsLi) {
    itemsLi.each(function(itemLi) {
        var el = new Element('li'),
            name = new Element('a', {
                'html': itemLi.title
            }).inject(el);
        if (itemLi.items) {
            var ul = new Element('ul').inject(el)
            for(var i = 0; i < itemLi.items.length; i++){
                var li = new Element('li').inject(ul);
                    subItem = new Element('a', {
                        'html': itemLi.items[i].title
                    }).inject(li);
            }
        };

        el.inject(gallery);
    });
};

Upvotes: 2

Prusse
Prusse

Reputation: 4315

You need to loop through the sub items also, try:

var addItemsLi = function(itemsLi){
    itemsLi.each(function(itemLi){
        var el = new Element('li'),
            name = new Element('a', {'html': itemLi.title}).inject(el);
        if (itemLi.items){
            var ul = new Element('ul');
            itemLi.items.each(function(item){
                var li = new Element('li').inject(ul),
                subItem = new Element('a', {'html': item.title}).inject(li);
            });
        };
        el.inject(gallery);
    });
};

Upvotes: 1

Related Questions