问题
Given the following data format, how can the data be grouped by their keys?
The format of the data is:
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"
}]
The expected output is:
[{
"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"
}]
回答1:
Pseudo Code
Here's the solution in general, for each object in the collection,
- Verify that each key does not exist in the result set.
- If the key exists and the result is not equal to the value, then
- Convert the value to an array and keep all unique values.
- Otherwise, set the value at this key to the value.
Problems
It's not defined in your question whether or not you want unique results. I suspect that the result set should not be unique for some keys. In which case, you should modify the logic within the each
to reflect that logic. As an example, you probably want billamount
to all duplication, but you want billingid
to be unique.
Code
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;
} );
来源:https://stackoverflow.com/questions/22819116/how-to-group-a-collection-of-data-by-its-keys-using-underscore-js