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();
4
  • 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:17
  • @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. Commented Jan 27, 2014 at 17:18
  • any chance you can explain that simplified version, i dont get it ;p Commented Jan 27, 2014 at 17:19
  • @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. Commented Jan 27, 2014 at 17:22
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);
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.