简体   繁体   中英

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...

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM