analyse : function (that) {
var a = new Array();
var x = 0;
$(that).children("li").each(function(){
console.log('test1');
a[x]['name'] = 'f';
a[x]['link'] = 'UUUUUUUUUUU';
console.log('test2');
x++;
})
return a;
}
I’m trying to create an array to store the hierarchy from my menu for PHP later on.
The console won’t show me “test2”, what did I do wrong?
Transformed into this with Didier G’s Help:
analyse : function (that) {
return $(that).children('li').map(function() {
var b = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b.childs = mcms.module.analyse($(this).children('ul'));
}
return b;
});
}
So if i say var y = analyse('#menu'); I get the whole bunch! ^^
'a[x]'is undefined at that moment. You have to first build an object and assign it to ‘i’ position (‘x’ is indeed a not standard name for an iterator, thanks @Cito):Note: your code misses a
;after the each(). Even though it is valid javascript to omit semi-colons, it is I think better to explicitly use them to avoid misinterpretations.Creating array can be achieve by using .map()
Here’s a jsfiddle to illustrate
This article covers a the use of .each() and .map() for building data collections out of lists in jquery.