0

Im trying something which is probably very easy but i cant seem to find out why its not working. Im trying to dynamically create and array with jquery/javascript.

my code;

var icons = $('.icon');

var desktopicons = [];

var user = { name: username };

var iconsetup = { myicons: [] };

desktopicons.push(user);
desktopicons.push(iconsetup);

$.each(icons, function() {
        var name = $(this).attr('name');
    var rel = $(this).attr('rel');


    var icon = { 
        icon: [{
            name: name,
            rel: rel
        }]
    };

    iconsetup.myicons[0].push(icon);

});

desktopicons.push(user);
desktopicons.push(iconsetup);

$('#desktop').append(desktopicons[0].name);
$('#desktop').append(desktopicons[1].myicons[0].icon[0].name);

Somehow my log file says cannot call method push of undefined on 'iconsetup.myicons[0].push(icon);' this line.

Anyone who can tell me how to create the array? Thanks!

4
  • iconsetup.myicons.push(icon); Commented Jan 27, 2014 at 17:09
  • iconsetup.myicons is an empty array. Commented Jan 27, 2014 at 17:09
  • You don't need the [0], iconsetup.myicons.push(icon); Commented Jan 27, 2014 at 17:09
  • its unclear to me when to use the [0] and when not.. myicons is an array i thought cuz i declared myicons: [] in var iconsetup Commented Jan 27, 2014 at 17:16

3 Answers 3

6

You are using myicons[0] which means you get the first item of the myicons and that is not an array

Use

iconsetup.myicons.push(icon);

You could also simplify the whole .each() section with

iconsetup.myicons = icons.map(function(idx, item){
   return {icon:[{name: item.name, rel: item.rel}]}
}).get();
Sign up to request clarification or add additional context in comments.

4 Comments

its unclear to me when to use the [0] and when not.. myicons is an array i thought cuz i declared myicons: [] in var iconsetup
@MartijnMichel myicons is an array, and so myicons[0] works but it returns the first item in that array. And that item is not an array.
any chance you can explain that simplified version, i dont get it ;p
@MartijnMichel about the map() method see api.jquery.com/map It really is just a slight optimization. If you feel uncomfortable with that code, feel free to ignore it. Your own approach is perfectly fine.
0

You are trying to push the icon to myicons[0] which is undefined, instead you need to push to myicons which will add the icons to your array:

iconsetup.myicons.push(icon);

Comments

0

You never set iconsetup.myicons[0] equal to anything. iconsetup.myicons is simply an empty array with nothing in it, and no element 0. Maybe you meant:

iconsetup.myicons.push(icon);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.