tags:

views:

13

answers:

1

I need to dynamically create a json object full of cats and sub cats. My structure looks like this

var cats = {
      tops: {
         'top' : {
            link : 'link',
          subs : [
               {
                  'sub' : {
                     link : 'a link'
                  }
               }
            ]
         }
      }
   };

Now I can add a top level category no problem with cats.tops[topVar] = { link : topLinkVar };

However I need to add subs categories to the top category.

I have tried a few variations such as cats.tops[topVar].subs.push( { subVar : { link : subLinkVar } } ); But this produces an undefined error.

The trick is that the sub categories need to be an array, so each top category can have many sub categories. What am I missing?

A: 

This is why coding on a saturday is bad idea. Also I am rather new to JSON.

Anyway.

The reason why I was getting the undefined error is because my new top category did not create the subs array.

The proper syntax to create the new top category looks like this:

cats.tops[topVar] = {link : topLinkVar, subs : [] };

Now

cats.tops[topVar].subs.push( { subVar : { link : subLinkVar } } );

Will work as expected

Mike