初始数组的一个示例:
jobListRecords = [
{
"customerID" : "1",
"name" : "Larry Bird",
"serviceID" : "101",
"serviceName" : "Dog Walking"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
期望的结果
sortCustomer示例:
sortCustomer = [
{
"customerID" : "1",
"name" : " Larry Bird",
"jobArray" : [
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"jobArray" : [
{
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
}
他们是一种简单有效的解决方法,无需迭代所有数据3次以上。谢谢你的时间,下面是我尝试过的几件事之一。
我尝试使用我发现的一个例子来解决这个问题,但它将所有serviceID组合在一起,这不是我需要的。
DID不能正常工作的示例。
jobListGrouped = _
.chain(jobListRecords)
.groupBy('customerID')
.map(function(value, key) {
return {
CustomerID: key,
services: _.pluck(value, 'serviceID')
}
})
.value();
答案 0 :(得分:1)
您pluck
只将serviceIDs
放入该数组中。相反,你需要做类似
.map(function(values, key) {
return {
customerID: key,
name: values[0].name.
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
或甚至更明确
.map(function(values, key) {
return _.extend(_.omit(values[0], 'serviceID', 'serviceName'), {
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
(partial
调用与function(value) { return _.pick(value, 'serviceID', 'serviceName'); }
)