Best way to grab each subcategory?


#1

I want a way to display Subcategory and those items that belong to the subcategory underneath it using a list or materialiecss collection. I don’t want to repeat subcategory a bunch of times, so I came up with this helper function. This gives me all of my subcategories and ensures I don’t post. But, how do I get the other items that are associated with this subcategory only and display them properly? Can somebody show me how to do this in meteor?

–Header
-----Subcategory
-------item 1
------ item 2
----Subcategory
------item 1
---- item 2

     cats: function() {
            var everything = Uploads.find({'metadata.category': this.name}, {fields: {'metadata.subcategory':1}}).fetch();
        
          var subs = [];
          for (var i in everything) {
          subs.push(everything[i].metadata.subcategory);
        
        
            }
  return _.uniq(subs);
  }

#2

Your data structure is pretty complicated, I guess. I assume you have some kind of parent/child connection.

There is similar question (and answer) on SO: http://stackoverflow.com/questions/32641846/meteor-model-tree-structure-best-way-getting-id-and-how-to-create-nested-list-o

http://meteorpad.com/pad/ccTRc7dszJr4B34Xw/Meteor-Tree

I hope this will help you.


#3

And how are these “other” items associated? Cause you did not describe your data structure at all.
If it is part of Uploads, it should be quite easy

cats: function() {
    var everything = Uploads.find({'metadata.category': this.name}, {fields: {'metadata.category':1, 'itemData': 1 }}).fetch();

    var subs = [];
    for (var i in everything) {
      subs[everything[i].metadata.subcategory].push(everything[i].itemData);
    }
  }

In that for cycle u should check if subs[everything[i].metadata.subcategory] property exist and if not than =[]; before pushing.
And than transform it to normal array using Object.keys so #each can iterate over it.

  <template name="parent">
    {{#each categories}}
      {{> category}}
    {{/each}}
  </template>

  <template name="category">
    {{category_name}}
    {{#each items}}
      {{> item}}
    {{/each}}
  </template>