如何使用lodash重新组织对象数组

时间:2017-02-15 12:16:22

标签: javascript lodash

我有没有办法用lodash制作A到B?赞赏。

A - 原始数组如下所示。

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

B - 我希望它像下面那样。

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

3 个答案:

答案 0 :(得分:3)

使用Array.prototype.reduce()Object.keys()函数的

JS解决方案:



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);




答案 1 :(得分:2)

这是一个lodash解决方案,它使用groupBy按照customerNamemap对集合进行分组,以转换每个分组的项目,然后再次使用map来获取所有<{1}}在分组集合中。

customerId

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; }

答案 2 :(得分:0)

_.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);
}, []);