考虑到以下数据格式,如何通过密钥对数据进行分组?
数据格式为:
data=[
{
"billingid": 138,
"amount": "800",
"billamount": "200",
"balance": "1",
"paid": "810",
"billdate": "Apr 2, 2014 12:00:00 AM",
"tax": "11",
"patientid": "TMCH17",
"configid": 6,
"paymenttype": "cash",
"servicename": "Room",
"firstname": "kannan"
},
{
"billingid": 138,
"amount": "800",
"billamount": "500",
"balance": "1",
"paid": "810",
"billdate": "Apr 2, 2014 12:00:00 AM",
"tax": "11",
"patientid": "TMCH17",
"configid": 3,
"paymenttype": "cash",
"servicename": "Lab",
"firstname": "kannan"
},
{
"billingid": 138,
"amount": "800",
"billamount": "100",
"balance": "1",
"paid": "810",
"billdate": "Apr 2, 2014 12:00:00 AM",
"tax": "11",
"patientid": "TMCH17",
"configid": 1,
"paymenttype": "cash",
"servicename": "Consultation",
"firstname": "kannan"
}]
预期输出为:
[{
"billingid": 138,
"amount": "800",
bamount:[{
"billamount": "100",
"billamount": "200",
"billamount": "300"
}],
"balance": "1",
"paid": "810",
"tax": "11",
"patientid": "TMCH17",
"configid": 1,
"paymenttype": "cash",
service[{
"servicename": "Consultation",
"servicename": "room",
"servicename": "lab",
}],
"firstname": "kannan"
}]
答案 0 :(得分:0)
以下是集合中每个对象的解决方案,
您的问题中未定义您是否需要独特的结果。我怀疑结果集对于某些键不应该是唯一的。在这种情况下,您应该修改each
中的逻辑以反映该逻辑。例如,您可能希望billamount
进行所有重复,但您希望billingid
是唯一的。
var summary = _.reduce(data, function(result, object) {
_.each(object, function(value, key) {
result[key] = ( _.has(result, key) && result[key] !== value ?
_.uniq(_.flatten([result[key], value])) : value);
});
return result;
} );