【问题标题】:group objects array underscore js组对象数组下划线js
【发布时间】:2015-01-29 17:00:58
【问题描述】:

我从一个如下所示的 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 完成这项工作? 很想得到一个使用下划线的解决方案,因为我们在整个项目中都在使用它,它看起来更干净,所以......

【问题讨论】:

    标签: javascript underscore.js


    【解决方案1】:

    您应该能够使用下划线的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>

    【讨论】:

    • 请检查更新(接受时正在处理)。 IMO 现在干净多了,只需使用下划线方法。
    • var arranged = _.map(_.groupBy(data, 'product_id'), function(item, key) { return { product_id: key, offers :_.map(item, _.partial(_.omit, _, 'product_id')) } });
    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2018-04-11
    • 2023-03-23
    相关资源
    最近更新 更多