How to group a collection of data by its keys using Underscore.js?

人走茶凉 提交于 2019-12-13 22:07:32

问题


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,

  1. Verify that each key does not exist in the result set.
  2. If the key exists and the result is not equal to the value, then
    1. Convert the value to an array and keep all unique values.
    2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!