簡體   English   中英

組對象數組下划線js

[英]group objects array underscore js

我從URL看到這樣的數組:

[
   {
     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
   },
]

我想將此轉換為:

[
   {
     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
     }]
   },
]

任何知道如何使用下划線js完成此操作的人? 很想使用下划線獲得解決方案,因為我們在整個項目中使用它並且它看起來更干凈,所以...

您應該能夠使用下划線的groupBy方法對它們進行分組,盡管它不會( groupBy )從每條記錄中刪除product_id。 然后,您可以獲取每個鍵並將它們用作數組元素。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM