且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

组对象数组下划线js

更新时间:2022-10-19 14:09:37

你应该可以使用 underscore 的 groupBy 方法对它们进行分组,尽管它不会(单独)从每个记录中删除 product_id.然后,您可以获取每个键并将它们用作数组元素.

var data = [{编号:1,产品编号:101,price_new: 100,price_old: 90}, {编号:2,产品编号:101,price_new: 100,price_old: 90}, {编号:3,产品编号:102,price_new: 100,price_old: 90}, ];var grouped = _.chain(data).groupBy("product_id").map(function(offers, product_id) {//可选地从每条记录中删除 product_idvar cleanOffers = _.map(offers, function(it) {return _.omit(it, "product_id");});返回 {产品 ID:产品 ID,优惠:清洁优惠};}).价值();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>

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>