jhlosin
jhlosin

Reputation: 575

how to reorganize an array of object using lodash

Is there a way I can make A to B using lodash? Appreciated.

A - Original array looks like below.

[
      {
        "customerId": 5458122321,
        "customerName": "C1"
      },
      {
        "customerId": 5461321801,
        "customerName": "C1"
      },
      {
        "customerId": 5434315807,
        "customerName": "C2"
      }
    ]

B - and I want it to be something like below.

[
      {
        "customerId": [5461321801, 5458122321]
        "customerName": "C1"
      },
      {
        "customerId": [5434315807],
        "customerName": "C2"
      }
    ]

Upvotes: 2

Views: 120

Answers (3)

ryeballar
ryeballar

Reputation: 30098

Here's a lodash solution that makes use of groupBy to group the collection by their customerName, map to transform each grouped items and then use map again to get all customerId in a grouped collection.

var result = _(source)
  .groupBy('customerName')
  .map(function(group, name) {
    return {
      customerId: _.map(group, 'customerId'),
      customerName: name
    };
  }).value();

var source = [
      {
        "customerId": 5458122321,
        "customerName": "C1"
      },
      {
        "customerId": 5461321801,
        "customerName": "C1"
      },
      {
        "customerId": 5434315807,
        "customerName": "C2"
      }
];

var result = _(source)
  .groupBy('customerName')
  .map(function(group, name) {
    return {
      customerId: _.map(group, 'customerId'),
      customerName: name
    };
  }).value();

console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Upvotes: 2

stasovlas
stasovlas

Reputation: 7416

solution with _.reduce

var B = _.reduce(A, function(result, item) {
    var addedItem = _.find(result, {customerName: item.customerName});
    if (addedItem) {
        addedItem.customerId.push(item.customerId);
        return result;
    }
    item.customerId = [item.customerId];
    return _.concat(result, item);
}, []);

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Pure JS solution using Array.prototype.reduce() and Object.keys() functions:

var A = [
        { "customerId": 5458122321, "customerName": "C1" }, { "customerId": 5461321801, "customerName": "C1" }, { "customerId": 5434315807, "customerName": "C2" }
    ],
    // accumulating an object "indexed" by 'customerName' attributes 
    // for grouping 'customers' by same name
    B = A.reduce(function (r, o) {
        (r[o.customerName])?
            r[o.customerName]["customerId"].push(o.customerId)
            : r[o.customerName] = {customerId: [o.customerId], customerName: o.customerName};

        return r;
    }, {}),
    
    // getting values from the object 'B'
    result = Object.keys(B).map(function(k){ return B[k]; });

console.log(result);

Upvotes: 3

Related Questions