Prateek
Prateek

Reputation: 299

Grouping Of Data in AngularJs

I am building a site for a restaurant . On the site I am rendering the restaurant menu on a page .

The Menu Items Json, I am getting from server looks like this : -

{
    "_id" : ObjectId("54c3c6e6cd7fe7df22cae87e"),
    "restaurant" : ObjectId("54b3a7ef613e89f64654f2b3"),
    "name" : "Pasta",
    "itemCode" : "PST",
    "price" : 240,
    "sellingPrice" : 280,
    "cuisine" : "Ittalian",
    "category" : "starter",
    "type" : "non-veg",
    "created" : ISODate("2015-01-24T16:23:02.652Z"),
    "Head" : pasta
    "__v" : 0
}

So basically the requirement is to group menu items on basis of head field (which can be soups, pizza, pastas,etc).

so that all the item with "head" : "soups" will list down together and all item with "head" : "pizza" will list down together .

The way I thought of doing this is through designing custom filter, where I will pass all the unique "head" attribute and I will get data accordingly .

Just need a better and more optimize approach for the situation .

Upvotes: 0

Views: 55

Answers (2)

Daniel
Daniel

Reputation: 423

Depending on how often that filter will be called, you should probably just postprocess the data and create a new result set, grouped by the correct value. Something like (untested):

var jsonResults = [{head:'pasta',...},{head:'soups',...}]; 
  , jsonResultsProcessed = { };
  , rec

for(var i=0; i<jsonResults.length; i++) {
   rec = jsonResults[i];
   if(!jsonResultsProcessed[rec.head]) {
       jsonResultsProcessed[rec.head] = [ rec ];
   } else {
       jsonResultsProcessed[rec.head].push(rec);
   }
}

$scope.results = jsonResultsProcessed;

and then in your view, you can just refer to results.pizza or whatever.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

var dishesPerHead = {};
var heads = [];
angular.forEach(dishes, function(dish) {
    var dishesForHead = dishesPerHead[head];
    if (!dishesForHead) {
        dishesForHead = [];
        heads.push(dish.head);
        dishesPerHead[dish.head] = dishesForHead;
    }
    dishesForHead.push(dish);
}

Now you have an array of distinct heads, and for each head, dishesPerHead contains the array of dishes having this head.

Upvotes: 0

Related Questions