2

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

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Please check the updates (was working on them when you accepted). It's much cleaner now, IMO, just using underscore methods.
var arranged = _.map(_.groupBy(data, 'product_id'), function(item, key) { return { product_id: key, offers :_.map(item, _.partial(_.omit, _, 'product_id')) } });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.