Reputation: 1126
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);
});
Upvotes: 1
Views: 42
Reputation: 19828
You have to change function invocation or function declaration because they are not compatible. Change in declaration is following:
var getMenuItem = function () { //removed unnecessary argument
OR change invocation to
getMenuItem(MENU) // pass MENU as argument
Upvotes: 1
Reputation: 388436
Your function getMenuItem
expects a argument which is iterated over, but in your call you are not passing any parameter, so MENU
inside the function is undefined thus the error.
So change
getMenuItem();
to
getMenuItem(MENU);
If you don't want to pass the menu instance to the function and want to use the shared variable MENU
then remove the argument declaration from the function definition ie change var getMenuItem = function (MENU) {
to
var getMenuItem = function () {
//now here MENU will refer to the MENU variable in the shared scope
}
Upvotes: 3