有没有办法使用 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/