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

标签 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"
      }
    ]

最佳答案

使用 Array.prototype.reduce() 的 JS 解决方案和 Object.keys()功能:

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

关于javascript - 如何使用 lodash 重新组织对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42249170/

相关文章:

javascript - 如何使用 d3 从嵌套的 JSON 数组中调用数据?

javascript - 是否有用于桌面的元标记或类似视口(viewport)初始比例的东西?

javascript - 为什么传入的参数在一个地方有效,但在另一个地方却无效?

javascript - 在循环递归期间,索引计数丢失

javascript - Lodash 标题大小写(每个单词的首字母大写)

javascript - 从sql server获取日期时间字段

javascript - 映射对象内的数组

javascript - 在 _.map() 中使用异步函数

javascript - 在 Lodash 中不使用循环获取对象的父对象

javascript - JS : sort array on date and time