mardi 5 mai 2015

When using an $.each statement on my json object I get an error

When using an $.each statement on my json object I get an 'Uncaught TypeError: Cannot read property 'length' of undefined'. I know my $.each statement is causing it because when I comment it out the console.log returns [Object, Object, Object] as expected. What I'm trying to do is iterate through the object and return the value of title.

$(function () {
var MENU = [
    {
        'title': 'Item 1',
        'submenu': null
    },
    {
        'title': 'Item 2',
        'submenu': null
    },
    {
        'title': 'Item 3',
        'submenu': [
            {
                'title': 'Sub 1',
                'submenu': null
            },
            {
                'title': 'Sub 2',
                'submenu': null
            },
            {
                'title': 'Sub 3',
                'submenu': [
                    {
                        'title': 'SubSub 1',
                        'submenu': null
                    },
                    {
                        'title': 'SubSub 2',
                        'submenu': null
                    },
                    {
                        'title': 'SubSub 3',
                        'submenu': null
                    }
                ]
            }
        ]
    }
];

var getMenuItem = function (MENU) {
    $.each(MENU, function (key, value) {
        var title = value.title;
        $('#myMenu').append('<ul>' +'<li>' + title +'</li>' + '</ul>' );


    });
    console.log(MENU);

};
getMenuItem();



console.log(MENU);

});

Aucun commentaire:

Enregistrer un commentaire