Erik van de Ven
Erik van de Ven

Reputation: 4975

group objects array underscore js

I'm getting an array back from an URL which looks like this:

[
   {
     id : 1,
     product_id : 101,
     price_new : 80,
     price_old : 90
   },
   {
     id : 2,
     product_id : 101,
     price_new : 80,
     price_old : 90
   },
   {
     id : 3,
     product_id : 102,
     price_new : 80,
     price_old : 90
   },
]

I would like to transform this, to:

[
   {
     product_id : 101,
     offers : [
     {
       id: 1
       price_new : 80,
       price_old : 90
     },{
       id: 2
       price_new : 80,
       price_old : 90
     }]
   },
   {
     product_id : 102,
     offers: [{
       id : 3,
       price_new : 80,
       price_old : 90
     }]
   },
]

Anyone who knows how to get this done using underscore js? Would love to get a solution using underscore cause we're using it in our entire project and it looks more clean, so...

Upvotes: 2

Views: 3061

Answers (1)

ssube
ssube

Reputation: 48247

You should be able to use underscore's groupBy method to group them, although it won't (on its own) remove the product_id from each record. You can then take each key and use them as array elements.

var data = [{
  id: 1,
  product_id: 101,
  price_new: 100,
  price_old: 90
}, {
  id: 2,
  product_id: 101,
  price_new: 100,
  price_old: 90
}, {
  id: 3,
  product_id: 102,
  price_new: 100,
  price_old: 90
}, ];

var grouped = _.chain(data).groupBy("product_id").map(function(offers, product_id) {
  // Optionally remove product_id from each record
  var cleanOffers = _.map(offers, function(it) {
    return _.omit(it, "product_id");
  });

  return {
    product_id: product_id,
    offers: cleanOffers
  };
}).value();

document.getElementById("results").textContent = JSON.stringify(grouped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<pre id="results"></pre>

Upvotes: 4

Related Questions